[英]Role Based access to routes in laravel
在下面我只想在用戶角色是管理員時訪問路由獲取產品。 我怎樣才能做到這一點?
數據庫中的用戶 Model
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('role');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
產品 Model
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('slug');
$table->string('description')->nullable();
$table->decimal('price',5,2);
$table->timestamps();
});
}
Api.php
Route::group(['middleware' => ['authentic']], function () {
Route::get('/products',[ProductController::class,'index']);
});
管理員中間件
public function handle($request, Closure $next)
{
if(auth()->user()->role == 'admin'){
return $next($request);
} else if(auth()->user()->role == 0){
return $next($request);
}
return redirect('home')->with('error', "You have no proper authentication to access the area!");
}
// 和上面一樣
`Route::group(['middleware' => ['role:admin']], function () {
Route::get('/products',[ProductController::class,'index']);
});`
//或者你可以單獨做
`Route::group(['middleware' => ['role:admin']], function () {
Route::get('/products',[ProductController::class,'index'])->middleware('role:cashier');
Route::post('/products',[ProductController::class,'index'])->middleware('role:manager');
});`
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.