[英]Role Based access to routes in laravel
In the below I want to access the route get product only if the user role is admin.在下面我只想在用户角色是管理员时访问路由获取产品。 How can I do that?
我怎样才能做到这一点?
User Model in database数据库中的用户 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();
});
}
Product Model产品 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 Api.php
Route::group(['middleware' => ['authentic']], function () {
Route::get('/products',[ProductController::class,'index']);
});
AdminMiddleware管理员中间件
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!");
}
// Like above // 和上面一样
`Route::group(['middleware' => ['role:admin']], function () {
Route::get('/products',[ProductController::class,'index']);
});`
// OR you can do individually //或者你可以单独做
`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.