修改AuthController 程式碼:
到POSTMAN設定,每次都不一樣~
TOKEN 是eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9....
:貼上TOKEN
設定 路由:
設定完要讓伺服器重跑,才可以再測試成功:
確保你的 AuthController 被正確加載了,嘗試運行:
可以做登出的
修改AuthController 程式碼
增加路由
POSTMAN測試
帶入token
修改測試網址: localhost:8000/logout
到localhost:8000/user顯示
oauth_access_tokens資料庫查看
修改Authenticate 程式碼
修改前程式碼:
<?php
namespace App\Http\Middleware;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
class Authenticate extends Middleware
{
/**
* Get the path the user should be redirected to when they are not authenticated.
*
* @param \Illuminate\Http\Request $request
* @return string|null
*/
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
return route('login');
}
}
}
修改後程式碼:
到 Handler程式碼加入套件:
修改後程式碼:
下面增加程式碼:
POSTMAN測試
再測試登入一次,拿到新的token
POSTMAN用POST貼email:joe@gmail.com
password:12345678 在localhost:8000/login
在GET在貼上新的TOKEN成功登入
在localhost:8000/user
把token隨便移掉一個字顯示
在購物車加上 user id
先用指令: php artisan make:migration add_user_id_to_carts
修改AddUserIdToCarts 程式碼
程式碼修改前:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AddUserIdToCarts extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('carts', function (Blueprint $table) {
//
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('carts', function (Blueprint $table) {
//
});
}
}
先把users資料表把id原來是1的改成0
程式碼修改後:
在terminal下指令php artisan migrate
到carts資料表查看多了user_id欄位
按carts資料表查看 把手
選Foreign key都有加上
修改 Cart程式碼:
修改前程式碼:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Cart extends Model
{
use HasFactory;
public function cartItems()
{
return $this->hasMany(CartItem::class);
}
}
修改後程式碼: 加入protected $guarded = [''];
修改路由:
修改前程式碼:
修改後程式碼:
修改CartController 程式碼:
程式碼修改前:
public function index()
{
$cart = Cart::with(['cartItems'])->firstOrCreate();
return response($cart);
}
程式碼修改後:
用POSTMAN測試
POST在localhost:8000/signup
貼上name:joe2
email:joe2@gmail.com
password:12345678
password_confirmation:12345678
測試登入
用POST在localhost:8000/login
貼上email:joe2@gmail.com
password:12345678
拿到新的TOKEN
把token貼到
GET在localhost:8000/carts
先加入資料
查看
大家明天見~