我是 Laravel 的新手,不知道 Laravel 限制机制,我已经阅读了中间件,但对如何使用它以及为什么使用它以及它如何工作感到困惑,所以请指导我如何实现它以实现限制目的,即对于身份验证,sa 用户路由。
Make Sure your have role column or attribute in database users table.
STEP 1
Create a Midlleware
php artisan make:middleware AnyNameYouWant
it will create a nice boilerplate for you.
STEP 2
public function handle($request, Closure $next)
{
if (\Auth::user()->role == 'admin') {
return $next($request);
}
return redirect('home');
}
STEP 3
Use this in Kernel
protected $routeMiddleware = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'admin' => \App\Http\Middleware\YourMiddleware::class,
];
STEP 4
Protect your routes.
Route::get('admin/profile', function () {
//
})->middleware('admin');
You are done
The best way to learn is straight from the Laravel docs: https://laravel.com/docs/5.4/middleware
or you can just watch a short Laracasts video:https://laracasts.com/series/laravel-5-from-scratch/episodes/14
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.