mardi 23 août 2016

Laravel 5: Using session flash messages on routes with middleware?

I am working on a project that requires me to protect some routes. Therefore I created a middleware to filter the routes. I used the command:

php artisan make:middleware MustBeAdmin

I registered this middleware in my kernel.php file inside the App\Http directory as follows:

protected $routeMiddleware = [
               //   ...
    'isAdmin' => \App\Http\Middleware\MustBeAdmin::class,
];

and here is my implementation of the middleware class:

public function handle($request, Closure $next, $rights = 'user')
{
    $user = $request->user();

    if ($user && $user->isAdmin($rights)) {
        return $next($request);
    }
    return redirect('/');
}

The isAdmin() method is a User model method that checks if the user trying to login is admin or not. Here is it's implementation:

public function isAdmin($rights='user'){
    if ($rights) {
        return $this->rights == $rights;
    }

    return !! $this->rights;   
}

These routes can only be accessed by logged in admins.

Route::group(['middleware' => 'isAdmin:admin'], function(){
    Route::get('/', ['as' => 'admin/', 'uses' => 'AdminController@home']);
    Route::get('register/', ['as' => 'admin/register', 'uses' => 'AdminController@register']);
    Route::post('register/', ['as' => 'admin/register', 'uses' => 'AdminController@addAdmin']);
});

Now an attempt to access these routes by any user who is not an admin will redirect the user to the landing page, as specified by the line return redirect('/'); in the middleware.

Now here is my problem: How do I get it to redirect to the home page with a session message. Where do i set the session message since the request doesn't get to the AuthController? Is there some way to set a session variable in routes?

I know a constructor can be used on the Controller but I don't want that because I woulds still like to normal users (non admins) to access those methods.

Thanks in advance...



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire