1

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?

1 Answer 1

3

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); } 
Sign up to request clarification or add additional context in comments.

4 Comments

I undestood that $redirectTo is for when you successfully login, is that correct?
@AguV sorry, my bad. $redirectTo is indeed for successful login, unauthorised redirects are handled in the middleware directly, see updated answer
A little comment, I've tryied and is (strpos($request->path(), 'admin') because path is a function not a property.
@AguV oops you are right :) I wrote the code right here on SO, my IDE would have fixed the error automatically :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.