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

Shopping cart management API

1.1 Create shopping cart model and migrate files

Run the commandphp artisan make:model Cart -m Create shopping cart model and migrate files:Create table field:

        Schema::create('carts'.function (Blueprint $table) {
            $table->id();
            $table->integer('user_id')->comment('users');
            $table->integer('goods_id')->comment('goods');
            $table->integer('num')->default(1)->comment('Quantity of goods');
            $table->integer('is_checked')->default(1)->comment('Select or not: 0=> No, 1=> Select');
            $table->timestamps();
        });
Copy the code

Run the migration command:php artisan migrate The shopping cart model sets the fields that the shopping cart allows for batch assignment:

    // Fields that allow batch assignment
    protected $fillable = ['user_id'.'goods_id'.'num'];
Copy the code


1.2 Creating a Shopping cart resource controller

Run the commandphp artisan make:controller Web/CartController --api:

1, write add method to shopping cart

    /** * join shopping */
    public function store(Request $request)
    {
        $request->validate([
            'goods_id'= >'required|exists:goods,id'.'num'= > [// The quantity must not exceed the inventory of the goods
                function ($attribute.$value.$fail) use ($request) {
                    $goods = Good::find($request->goods_id);
                    if ($value > $goods->stock) {
                        $fail("Quantity cannot exceed merchandise stock!"); }}]], ['goods_id.required'= >'Goods cannot be empty'.'goods_id.exists'= >'Goods do not exist'
        ]);
		// Check whether the shopping cart data exists
        $cart = Cart::where('user_id', auth('api') -> id())
                ->where('goods_id'.$request->input('goods_id'))
                ->first();

        if (!empty($cart)) {
            $cart->num = $cart->num + $request->input('num'.1);
            $cart->save();
            return $this->response->noContent();
        }
        Cart::create([
            'user_id' => auth('api')->id(),
            'goods_id'= >$request->input('goods_id'),
            'num'= >$request->input('num'.1)]);return $this->response->created();
    }
Copy the code


2. Methods of quantity increase and reduction

Add model associated items to the shopping cart model:

    /** ** ** */
    public function goods() {
        return $this->belongsTo(Good::class, 'goods_id'.'id');
    }
Copy the code

    /** * Update number */
    public function update(Request $request, Cart $cart)
    {
        $request->validate([
            'num'= > ['required'.'gte:1'.// Must be greater than or equal to 1
                function ($attribute.$value.$fail) use ($cart) {
                    if ($value > $cart->goods->stock) { // Use the association model to fetch the commodity model
                        $fail('Quantity cannot exceed maximum stock! '); }},// Can not exceed the inventory]], ['num.required'= >'Quantity cannot be empty'.'num.gte'= >'Quantity at least greater than 1',]);$cart->num = $request->input('num');
        $cart->save();

        return $this->response->noContent();
    }
Copy the code


3. Remove the shopping cart

    /** * remove the shopping cart */
    public function destroy(Cart $cart)
    {
        $cart->delete();
        return $this->response->noContent();
    }
Copy the code


Shopping cart list

The cart list is the data that requires additional items, so we create cart CartTransformer. PHP:


       

namespace App\Transformers;

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

class CartTransformer extends TransformerAbstract {
    // Additional imported data
    protected $availableIncludes = ['goods'];

    public function transform(Cart $cart) {
        return [
            'id'= >$cart->id,
            'user_id'= >$cart->user_id,
            'goods_id'= >$cart->goods_id,
            'num'= >$cart->num,
            'is_checked'= >$cart->is_checked,
        ];
    }

    /** * Additional commodity data */
    public function includeGoods (Cart $cart) {
        return $this->item($cart->goods, newGoodTransformer()); }}Copy the code

Shopping cart list method:

    /** * Shopping cart list */
    public function index()
    {
        $carts = Cart::where('user_id', auth('api')->id())->get(); // The current user's shopping cart list
        return $this->response->collection($carts.new CartTransformer());
    }
Copy the code


1.3 Creating a shopping cart resource route

        /** * shopping cart */
        $api->resource('carts', CartController::class, [
            'except'= > ['show'] // Exclude shopping cart details not required
        ]);
Copy the code


1.4 Test Effect

1. Test adding to shopping cart:


2. Test the number of updates You can see that the update succeeded.


Delete the shopping cart


Shopping cart listYou can see that additional information about the item has been read.

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.