1.購物車加上對應的user
php artisan make:migration add_user_id_to_carts
2.添上user_id.這邊使用foriegn Key的性質,利用constrained綁定table,然後排在id之後
public function up()
{
Schema::table('carts', function (Blueprint $table) {
$table->foreignId('user_id')->constrained('users')->after('id');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('carts', function (Blueprint $table) {
$table->dropConstrainedForeignId('user_id');
});
}
3.當設定好跑migrate欄位的時候再Carts的table(user_id)他會自動補上一個數字的零,但因為user註冊成功時他的ID代入1,所以我們必須要先將table(users)的第一筆資料改為零
4.接著跑migrate
4.接著回到Models/Cart去製作我們的商業邏輯,增加$guarded
5.設定路由,將cart and cartItem都必須經過我們AuthAPI,必須都要經過Token的檢查
6.接著到CartController修改函式,透過$user = Auth()→user();根據這個函式可以拿到通過驗證的USER資料
邏輯判斷,如果沒有這個會員的購物車則執行增加,如果有這個會員資料則回傳他的購物車