如何保护路线laravel-5.8

时间:2019-06-09 06:56:21

标签: laravel laravel-5.8 laravel-eloquent-resource

嗨,我希望只有管理员可以访问filecontroller路由,或者用户不能通过输入URL来访问:

这些是路线:

  Route::group(['middleware' => ['web','auth']], function(){
     Route::get('/', function () {
       return view('welcome');
     });

     Route::get('/home', function(){
   if (Auth::user()->admin == 0) {
    return view('home');
   } else {
    $users['users'] = \App\User::all();
    return view('layouts.master', $users);
   }
     });

     Route::resource('file','FileController');

  });

用户无法访问Route :: resource('file','FileController');如果他知道URL

2 个答案:

答案 0 :(得分:3)

使用middleware

以下命令创建名为Admin的新中间件

php artisan make:middleware Admin

这会在app / Http / Middleware目录中创建一个名为Admin.php的文件,看起来像

<?php namespace App\Http\Middleware;

use Closure;

class Admin {

    public function handle($request, Closure $next)
    {

        if ( Auth::check() && Auth::user()->isAdmin() )
        {
            return $next($request);
        }

        return redirect('home');

    }

}

然后,您需要将管理中间件添加到您的app / Http / Kernel.php文件中

protected $routeMiddleware = [
    'auth' => 'App\Http\Middleware\Authenticate',
    'auth.basic' => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth',
    'guest' => 'App\Http\Middleware\RedirectIfAuthenticated',
    'admin' => 'App\Http\Middleware\Admin', // this line right here
];

将管理中间件添加到路由。

 Route::resource('file','FileController')->middleware(Admin::class)

最后,您需要在用户模型中添加上面创建的isAdmin方法,以检查该用户是否为管理员。

class User extends Model
{
    protected $casts = [
        'is_admin' => 'boolean',
    ];

    public function isAdmin()
    {
        return $this->is_admin;
    }
}

答案 1 :(得分:1)

您可以使用laravel中间件

URL:https://laravel.com/docs/5.8/middlewarehttps://www.tutorialspoint.com/laravel/laravel_middleware.htm

并用于路由

Route::group(['middleware' => 'isAdmin'], function(){
    Route::get('user', 'user\UserController@index');
});