2

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

pro
  • 609
  • 4
  • 17
  • 40

2 Answers2

4

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;
    }
}
Ali Ghaini
  • 882
  • 6
  • 13
1

you can use laravel middleware

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

and use to route

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