Yes it is the best way. Full documentation on Middleware.
I have included a basic implementation and requires that you add an admin column to your users table. The example below will get you started.
- 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. (Within your routes.php file).
get('protected', ['middleware' => ['auth', 'admin'], function() {
return "this page requires that you be logged in and an Admin";
}]);
- 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.
public function isAdmin()
{
return $this->admin; // this looks for an admin column in your users table
}
- This will do the trick. If you run into any problems, please post what you have tried and which step you got up to and I'll try my best to help.