Agu V Agu V - 6 months ago 48
PHP Question

Can't properly redirect unsuccessful login on laravel 5.2

I'm making an app in Laravel 5.2.
I'm trying to implement an auth page for the backoffice.

In routes I've got a group and auth middleware:

Route::group(['prefix' => 'admin'], function () {
Route::group(['middleware' => 'auth'], function () {
Route::get('/', 'IndexController@admin_index')->name('admin_index');
Route::get('/logout', 'IndexController@admin_logout')->name('logout');
});

Route::get('/login', 'UsersController@admin_login')->name('login');
});


What I want to accomplish here is when I enter "/admin", if a user is logged, redirect to "/", if not, redirect to "/admin/login"

The current behavior is redirect to "/login" on unsuccessful login, how can I change that?

Answer

If you don't have any other auth-protected pages for regular users, you could simply modify Authenticate middleware, otherwise you probably need to extend Auth middleware to add support for multiple redirect points

Option 1, modifying middleware:

public function handle($request, Closure $next, $guard = null)
    {
        if (Auth::guard($guard)->guest()) {
            if ($request->ajax() || $request->wantsJson()) {
                return response('Unauthorized.', 401);
            } else {
                // Changing login to admin/login
                return redirect()->guest('admin/login');
            }
        }

        return $next($request);
    }

Option 2 - create one more auth middleware, let's say 'auth-admin', change handle() method of that as shown above, and apply that middleware to admin routes instead of 'auth' middleware.

Option 3 - add a conditional in handle() method

public function handle($request, Closure $next, $guard = null)
    {
        if (Auth::guard($guard)->guest()) {
            if ($request->ajax() || $request->wantsJson()) {
                return response('Unauthorized.', 401);
            } else {
                $destination = (strpos($request->path, 'admin') !== false) ? 'admin/login' : 'login';
                return redirect()->guest($destination);
            }
        }

        return $next($request);
    }