Laravel 5 中用于管理员或身份验证的 Laravel 中间件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42473005/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 15:25:00  来源:igfitidea点击:

Laravel middleware for admin or auth in laravel 5

phplaravel

提问by Muhammad Amir

i am new to laravel and don't know about laravel restriction mechanism, i have read about middleware but confused how to use it and why it is used and how this will works, so please guide me how i can implement it for restriction purposes i.e for auth, sa user routes.

我是 Laravel 的新手,不知道 Laravel 限制机制,我已经阅读了中间件,但对如何使用它以及为什么使用它以及它如何工作感到困惑,所以请指导我如何实现它以实现限制目的,即对于身份验证,sa 用户路由。

回答by Adnan Mumtaz

Make Sure your have role column or attribute in database users table.

确保您在数据库用户表中有角色列或属性。

STEP 1

第1步

Create a Midlleware

创建中间件

php artisan make:middleware AnyNameYouWant

it will create a nice boilerplate for you.

它将为您创建一个不错的样板。

STEP 2

第2步

 public function handle($request, Closure $next)
{
    if (\Auth::user()->role == 'admin') {
      return $next($request);
    }

      return redirect('home');
}

STEP 3

第 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

你完成了

回答by Paras

The best way to learn is straight from the Laravel docs: https://laravel.com/docs/5.4/middleware

最好的学习方法是直接从 Laravel 文档中学习: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

或者你可以只看一个简短的 Laracasts 视频:https://laracasts.com/series/laravel-5-from-scratch/episodes/14