Search code examples
laravellaravel-5.8laravel-eloquent-resource

how to secure routes laravel-5.8


hi I wants that only admin can access the filecontroller route, or user can't access by typing URL:

these are routes:

  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');

  });

User can't access Route::resource('file','FileController'); if he knows URL


Solution

  • use middleware

    The following command creates new Middleware called Admin

    php artisan make:middleware Admin
    

    This creates a file called Admin.php within the app/Http/Middleware directory that looks like

    <?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');
    
        }
    
    }
    

    You then need to add the Admin Middleware to your app/Http/Kernel.php file

    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
    ];
    

    Add the Admin Middleware to a route.

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

    Finally you need to add the isAdmin method we created above to your User model to check whether or not the user is an Admin.

    class User extends Model
    {
        protected $casts = [
            'is_admin' => 'boolean',
        ];
    
        public function isAdmin()
        {
            return $this->is_admin;
        }
    }