This is the 19th day of my participation in the Gwen Challenge in November. Check out the details: The last Gwen Challenge in 2021

First, address management

1.1 Creating an Address Model and Migrating Files

Run the commandphp artisan make:model Address -m Create table structure in migration file:

Schema::create('addresses'.function (Blueprint $table) {
            $table->id();
            $table->integer('user_id')->comment('user id');
            $table->string('name')->comment('Harvester');
            $table->integer('city_id')->comment('id in city table');
            $table->string('address')->comment('Full address');
            $table->string('phone')->comment('Mobile phone Number');
            $table->tinyInteger('is_default')->default(0)->comment('Default address 0=> not default, 1=> default');
            $table->timestamps();
            $table->index('user_id'); // query the index
        });
Copy the code

Run the commandphp artisan migrate:


1.2 Creating an Address Authentication Class

Run the commandphp artisan make:request Web/AddressRequest:Writing:

    public function rules()
    {
        return [
            'name'= >'required'.'city_id'= > ['required'.function ($attribute.$value.$fail) {
                    $city = City::find($value);
                    if (empty($city)) $fail('Cities don't exist'); },].'address'= >'required'.'phone'= >'required|regex:/^1[3-9]\d{9}$/',]; }/**
     * 提示消息
     */
    public function messages() {
        return [
            'name.required'= >'Consignee required'.'city_id.required'= >'Address cannot be empty'.'address.required'= >'Full address cannot be empty'.'phone.required'= >'Mobile phone number cannot be empty',]; }Copy the code


1.3 Configuring Address transform Create an ADDRESS resource API controller

Configure the model with fields that can be inserted in batches:

    use HasFactory;
    protected $fillable = ['user_id'.'name'.'phone'.'address'.'city_id'.'is_default'];
Copy the code


In the city.php model, write the linkage to find the parent:

    /** * find the parent */
    public function parent() {
        return $this->belongsTo(City::class, 'pid'.'id');
    }
Copy the code

Find the upper-level linkage data according to the area ID in the auxiliary function:

    /** * select * from ** * where */
    if(! function_exists('city_name')) {
        function city_name($city_id) {
            $city = City::where('id'.$city_id)->with('parent.parent.parent')->first();
            // $str = $city['parent']['parent']['parent']['name'] ?? '';
            // $str .= $city['parent']['parent']['name'] ?? '';
            // $str .= $city['parent']['name'] ?? '';
            // $str .= $city['name'] ?? '';
            $str = [ 
                $city['parent'] ['parent'] ['parent'] ['name']????' '.$city['parent'] ['parent'] ['name']????' '.$city['parent'] ['name']????' '.$city['name']????' '
            ];

            return trim(implode(' '.$str)); }}Copy the code

Create addresstransform.php and say:


       

namespace App\Transformers;

use App\Models\Address;
use League\Fractal\TransformerAbstract;

class AddressTransformer extends TransformerAbstract {
    public function transform(Address $address) {
        return [ 
            'id'= >$address->id,
            'name'= >$address->name,
            'city_id'= >$address->city_id,
            'city_name' => city_name($address->city_id),
            'phone'= >$address->phone,
            'address'= >$address->address,
            'is_default'= >$address->is_default,
            'created_at'= >$address->created_at,
            'updated_at'= >$address->updated_at, ]; }}Copy the code

Run the commandphp artisan make:controller Web/AddressController --api Write add delete change check and whether the default method:


      

namespace App\Http\Controllers\Web;

use App\Http\Controllers\BaseController;
use App\Http\Requests\Web\AddressRequest;
use App\Models\Address;
use App\Transformers\AddressTransformer;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class AddressController extends BaseController
{
    /** * my address list */
    public function index()
    {
        $address = Address::where('user_id', auth('api')->id())->get();
        return $this->response->collection($address.new AddressTransformer());
    }

    /** * Add address */
    public function store(AddressRequest $request)
    {
        Address::create([
            'user_id' => auth('api')->id(),
            'name'= >$request->input('name'),
            'phone'= >$request->input('phone'),
            'address'= >$request->input('address'),
            'city_id'= >$request->input('city_id'),]);return $this->response->created();
    }

    /** * Address details */
    public function show(Address $address)
    {
        return $this->response->item($address.new AddressTransformer());
    }

    /** * update the address */
    public function update(AddressRequest $request, Address $address)
    {
        $address->update([
            'user_id' => auth('api')->id(),
            'name'= >$request->input('name'),
            'phone'= >$request->input('phone'),
            'address'= >$request->input('address'),
            'city_id'= >$request->input('city_id'),
            'is_default'= >$request->input('is_default')]);return $this->response->noContent();
    }

    /**
     * 删除地址
     */
    public function destroy(Address $address)
    {
        $address->delete();
        return $this->response->noContent();
    }

    /** * Default address */
    public function isDefault(Address $address)
    {
        if ($address->is_default == 1) { 
            return $this->response->noContent(); // If the address has been changed to the default address, it is returned directly
        }
        try {
            DB::beginTransaction(); // Start things to prevent one setting from succeeding and the other from failing
            // Set all addresses to non-default
            $default_address = Address::where('user_id', auth('api')->id())
                ->where('is_default'.1)
                ->first();
            if (!empty($default_address)) {
                
                $default_address->is_default = 0;
                $default_address->save();
            }
            // Set the current setting to default
            $address->is_default = 1;
            $address->save();
            DB::commit();
            return $this->response->noContent();
        } catch (\Exception $e) {
            DB::rollback();
            throw $e; }}}Copy the code

1.4 Configuring Address Routing

 // Add, delete, and check the address
        $api->resource('address', AddressController::class);
        // Set the default address
        $api->patch('address/{address}/default', [AddressController::class, 'isDefault']);
Copy the code


1.5 Order address modification

Because there is no API related to address writing before, the address block is simulated fake data, now modify it:

// Address data
        $address = Address::where('user_id', auth('api')->id())
                    ->orderBy('is_default'.'desc')
                    ->get();

Copy the code


Another place to verify that the address exists when submitting an order is:

'address_id'= >'required|exixts:addresses,id'
Copy the code


1.6 Test Effect

1. Add an address

2. Address list

3. Change the IP address

4. Address details5. Delete the address6. Set the default address

If you find this article helpful on your way to learning PHP, please follow me to like and comment on it. Thank you, your blog is definitely another support for me to write.