iT邦幫忙

2025 iThome 鐵人賽

DAY 17
0
Modern Web

Laravel 是甚麼系列 第 17

假刪除

  • 分享至 

  • xImage
  •  

昨天的文章內容有些不能顯示~
貼到這裡
修改CartItem不用隱藏任何欄位

https://ithelp.ithome.com.tw/upload/images/20250818/20119035oXsaRqMZaz.png

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class CartItem extends Model
{
   use HasFactory;

   protected $guarded = [''];   
   protected $appends = ['current_price'];

   public function getCurrentPriceAttribute()
   {
       return $this->quantity * 10;
   }
   public function product()
   {
       return $this->belongsTo(Product::class);
   }
   public function cart()
   {
       return $this->belongsTo(Cart::class);
   }

}

修改CartItemController的程式碼,加入套件
use App\Models\Cart;
use App\Models\CartItem;
https://ithelp.ithome.com.tw/upload/images/20250818/20119035Jq7ue9MZEv.png

修改store 程式碼
修改前程式碼:

public function store(Request $request)
    {
$messages =[
'required' => ':attribute 是必要的',    
'between' => ':attribute 的輸入 :input 不在 :min 和 :max 之間'
];

        //$form = $request->all();
$validator = Validator::make($request->all(),[
    'cart_id'=>'required|integer',
    'product_id'=>'required|integer',
    'quantity'=>'required|integer|between:1,10'
],$messages);
if($validator->fails()){
    return response($validator->errors(),400);
}
$validateData = $validator->validate();

        //DB::table('cart_items')->insert(['cart_id' => $form['cart_id'],
        DB::table('cart_items')->insert(['cart_id' => $validateData['cart_id'],
//'product_id' => $form['product_id'],
'product_id' => $validateData['product_id'],
//'quantity' => $form['quantity'],
'quantity' => $validateData['quantity'],
'created_at' => now(),
'updated_at' => now()]);

//return response(true);
return response()->json(true);
    }

```
----

修改後程式碼:
---

```
public function store(Request $request)
    {
$messages =[
'required' => ':attribute 是必要的',    
'between' => ':attribute 的輸入 :input 不在 :min 和 :max 之間'
];

        //$form = $request->all();
$validator = Validator::make($request->all(),[
    'cart_id'=>'required|integer',
    'product_id'=>'required|integer',
    'quantity'=>'required|integer|between:1,10'
],$messages);
if($validator->fails()){
    return response($validator->errors(),400);
}
$validateData = $validator->validate();
$cart = Cart::find($validateData['cart_id']);
$result = $cart->cartItems()->create(['product_id' => $validateData['product_id'],
'quantity' => $validateData['quantity']]);
        
return response()->json($result);
    
    

POSTMAN測試顯示
https://ithelp.ithome.com.tw/upload/images/20250818/20119035AhSAuJQxky.png

https://ithelp.ithome.com.tw/upload/images/20250818/201190358hL9Mnjgkn.png

更新的程式碼:

修改前程式碼:

public function update(UpdateCartItem $request, $id)
    {
        $form = $request->validated(); 
        DB::table('cart_items')->where('id',$id)
        ->update([
'quantity' => $form['quantity'],
'updated_at' => now()]);

return response()->json(true);
    }

修改後程式碼:
https://ithelp.ithome.com.tw/upload/images/20250818/20119035NXE0vCEP09.png

public function update(UpdateCartItem $request, $id)
   {
       $form = $request->validated(); 
       $item = CartItem::find($id);
       $item->fill(['quantity'=>$form['quantity']]);
       $item->save();

return response()->json(true);
   }
   

POSTMAN測試localhost:8000/cart-items/2
https://ithelp.ithome.com.tw/upload/images/20250818/20119035OFl8iMSoFA.png
資料表查看:

https://ithelp.ithome.com.tw/upload/images/20250818/20119035gBarH1aUFr.png


修改後程式碼:改其他寫法
https://ithelp.ithome.com.tw/upload/images/20250818/20119035iSuqrYaRhV.png

public function update(UpdateCartItem $request, $id)
   {
       $form = $request->validated(); 
       $item = CartItem::find($id);
       //$item->fill(['quantity'=>$form['quantity']]);

       $item->update(['quantity'=>$form['quantity']]);
       //$item->save();

return response()->json(true);
   }

POSTMAN測試
https://ithelp.ithome.com.tw/upload/images/20250818/20119035RUmd8Kk0U4.png
資料表查看:
https://ithelp.ithome.com.tw/upload/images/20250818/20119035d0tjhFoPRP.png
修改 刪除的程式碼:

原來的程式碼:

public function destroy($id)
    {
        
        DB::table('cart_items')->where('id',$id)
        ->delete();

return response()->json(true);
    }

修改的程式碼:

public function destroy($id)
    {
        
        CartItem::find($id)->delete();

return response()->json(true);
    }

https://ithelp.ithome.com.tw/upload/images/20250818/2011903501vAqGGo94.png
POSTMAN測試
https://ithelp.ithome.com.tw/upload/images/20250818/20119035QGuhSU1kqN.png
資料表查看
https://ithelp.ithome.com.tw/upload/images/20250818/20119035M6wP8zDSYS.png


修改CartController程式碼

https://ithelp.ithome.com.tw/upload/images/20250818/20119035MhtdZe55rf.png

修改前程式碼

public function index()
    {
        $cart = DB::table('carts')->get()->first();
        if(empty($cart)){
            DB::table('carts')->insert(['created_at' =>now(),'updated_at' =>now()]);
            $cart = DB::table('carts')->get()->first();
        }
        $cartItems = DB::table('cart_items')->where('cart_id',$cart->id)->get();
        $cart = collect($cart);
        $cart['items'] = collect($cartItems);    

        return response(collect($cart));
    }

修改後程式碼
https://ithelp.ithome.com.tw/upload/images/20250818/201190359NTkTx93SC.png
加入套件use App\Models\Cart;
https://ithelp.ithome.com.tw/upload/images/20250818/20119035S0McQV9DZa.png

修改後程式碼

public function index()
   {
       $cart = Cart::with(['cartItems'])->firstOrCreate();

       return response($cart);
   }

先把資料庫資料刪掉
https://ithelp.ithome.com.tw/upload/images/20250818/20119035dBH1F19HgP.png
後再新增
https://ithelp.ithome.com.tw/upload/images/20250818/20119035Xz0uDUtYjI.png

POSTMAN測試
https://ithelp.ithome.com.tw/upload/images/20250818/20119035zvxMHKYPxj.png
關聯的資料表修改資料讓下面可以帶出資料
https://ithelp.ithome.com.tw/upload/images/20250818/20119035aEm00nMSbK.png
POSTMAN測試localhost:8000/carts

https://ithelp.ithome.com.tw/upload/images/20250818/20119035s3TzXX8viM.png


https://ithelp.ithome.com.tw/upload/images/20250818/20119035HlpUAKBhjy.png

軟刪除:畫面上看起來是刪除,在資料表中沒有被刪除
在terminal下指令php artisan make:migration add_soft_delete_to_cart-items
新增
https://ithelp.ithome.com.tw/upload/images/20250818/20119035rU3gHcCL5W.png
原來的程式碼:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class AddSoftDeleteToCartItems extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        //
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        //
    }
}

https://ithelp.ithome.com.tw/upload/images/20250818/20119035EQvqmb8QeF.png

加入程式碼:紀錄誰被刪除/刪除的時間

https://ithelp.ithome.com.tw/upload/images/20250818/20119035XG8rvRIPR5.png
在terminal下指令php artisan migrate
沒新增先手動加入跑完流程
https://ithelp.ithome.com.tw/upload/images/20250818/20119035FS3dchYA7r.png
資料表查看
https://ithelp.ithome.com.tw/upload/images/20250818/20119035fcE8Jy0TTG.png
改CartItem程式碼加入套件: use Illuminate\Database\Eloquent\SoftDeletes;
修改程式碼:
https://ithelp.ithome.com.tw/upload/images/20250818/20119035zQuCOBqTO4.png
修改程式碼變成強制軟刪除

use Illuminate\Database\Eloquent\SoftDeletes;

class CartItem extends Model
{
    use HasFactory, SoftDeletes;

    protected static function boot()
    {
        parent::boot();
        static::addGlobalScope('softDeletes', function ($builder) {
            $builder->whereNull('deleted_at');
        });
    }
}

https://ithelp.ithome.com.tw/upload/images/20250818/20119035QrZtsCPVtL.png
完整的程式碼:
https://ithelp.ithome.com.tw/upload/images/20250818/2011903507v7pOFQqN.png

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class CartItem extends Model
{
    //use HasFactory;
    //use SoftDeletes;
    use HasFactory, SoftDeletes;

    protected static function boot()
    {
        parent::boot();
        static::addGlobalScope('softDeletes', function ($builder) {
            $builder->whereNull('deleted_at');
        });
    }
    protected $guarded = [''];   
    protected $appends = ['current_price'];

    public function getCurrentPriceAttribute()
    {
        return $this->quantity * 10;
    }
    public function product()
    {
        return $this->belongsTo(Product::class);
    }
    public function cart()
    {
        return $this->belongsTo(Cart::class);
    }


}

https://ithelp.ithome.com.tw/upload/images/20250818/201190359wjtf9DwKV.png

https://ithelp.ithome.com.tw/upload/images/20250818/201190351fPzVqfxK4.png
到CartItemController修改程式碼
程式碼:

public function destroy($id)
    {
        
        CartItem::find($id)->delete();

return response()->json(true);
    }

https://ithelp.ithome.com.tw/upload/images/20250818/20119035HhtwRyiagL.png

php artisan serve跑起來
https://ithelp.ithome.com.tw/upload/images/20250818/20119035A7co5ohHkU.png
POSTMAN看GET
https://ithelp.ithome.com.tw/upload/images/20250818/20119035IuwGFQR1F9.png
POSTMAN看delete

資料表看

變成真的刪除的程式碼:
修改前:

public function destroy($id)
    {
        
        CartItem::find($id)->delete();

return response()->json(true);
    }

修改後:

public function destroy($id)
   {
       
       CartItem::withTrashed()->find($id)->forceDelete();

return response()->json(true);
   }
   

資料表看:15

https://ithelp.ithome.com.tw/upload/images/20250818/20119035tjapdSFDFO.png

https://ithelp.ithome.com.tw/upload/images/20250818/20119035mfkWEFpu7x.png
大家明天見~


上一篇
關於ORM
下一篇
會員註冊開始~
系列文
Laravel 是甚麼30
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言