You need to create a middleware for your route.
Use: php artisan make:middleware AdminMiddleware
.
You will find in your middleware folder a new file with this name.
Put your logic in your middleware, e.g.
public function handle($request, Closure $next)
{
if(Auth::check())
{
return $next($request);
}
else
{
return view('auth.login')->withErrors('You are not logged in');
}
}
Once you have done your logic in your middleware, you can either call it in the route or make the middleware apply to all routes.
If you want to add it to all routes, go to Kernel.php
and add it to the $middleware
array, e.g.
protected $middleware = [
'IlluminateFoundationHttpMiddlewareCheckForMaintenanceMode',
'IlluminateCookieMiddlewareEncryptCookies',
'IlluminateCookieMiddlewareAddQueuedCookiesToResponse',
'IlluminateSessionMiddlewareStartSession',
'IlluminateViewMiddlewareShareErrorsFromSession',
'AppHttpMiddlewareVerifyCsrfToken',
'AppHttpMiddlewareAdminMiddleware',
];
If you want to add it to specific routes only, add it to the $routeMiddleware
variable and add the alias to the route. E.g.
protected $routeMiddleware = [
'auth' => 'AppHttpMiddlewareAuthenticate',
'auth.basic' => 'IlluminateAuthMiddlewareAuthenticateWithBasicAuth',
'guest' => 'AppHttpMiddlewareRedirectIfAuthenticated',
'admin' => 'AppHttpMiddlewareAdminMiddleware',
];
You can then add it to a route, as a filter, e.g.
Route::get('admin/profile', ['middleware' => 'admin', function()
{
}]);
For additional info visit the docs:
http://laravel.com/docs/master/middleware
EDIT
An improvement on this would be to use variadic functions which was introduced in PHP 5.6
http://php.net/manual/en/migration56.new-features.php
Instead of having to make a middleware for each permission set you can do the following
PermissionMiddleware
namespace AppHttpMiddleware;
use Closure;
use AppModelsRole;
class PermissionMiddleware
{
// Pass parameters to this middleware
public function handle($request, Closure $next, ...$permitted_roles)
{
//Get a users role
$role = new Role;
$role_name = $role->getUserRoleByName();
foreach($permitted_roles as $permitted_role) {
if($permitted_role == $role_name) {
return $next($request);
}
}
return redirect()->back()->withErrors('You do not have the required permission');
}
}
Notice the ...$permitted_roles
Route::get('admin/profile', ['middleware' => 'PermissionMiddleware:Admin,Marketing', function()
{
}]);
You can now specify as many roles as required for one middleware rather than creating multiple by using middleware parameters
Docs
https://laravel.com/docs/5.3/middleware#middleware-parameters