Chathurika Mahanama Chathurika Mahanama - 6 months ago 12
PHP Question

How to group laravel routes based on logged users and guest users

I want to group the Laravel 5 routs based on the logged users and guest users. Is there any inbuilt framework methods in Laravel 5 to do this?

Answer

Yes, you can do this by updating following method in Authenticate.php

public function handle($request, Closure $next, $guard = null)
    {
        if (Auth::guard($guard)->guest()) {

            if ($request->ajax() || $request->wantsJson()) {
                return response('Unauthorized.', 401);
            } else {
                return redirect()->guest('login');
            }
        }

        return $next($request);
    }

If you are using Sentinel you can check the the logged user from

Sentinel::check() instead of Auth::guard($guard)->guest()

Then you can group the routs as follows.

Route::group(['middleware' => ['auth']], function () {
    // Authorized routs
});

Route::group(['middleware' => ['guest']], function () {
    // Guest routs
});
Comments