I have a custom login controller and its using return redirect()->intended(route('home'))
, as per the documentation this should send the user redirect the user to the URL they were attempting to access before being intercepted by the authentication middleware.
But for my case every time it is redirecting to home route
.I am sure i have done correctly or at least i think i have done correctly. Can anyone please tell me where i am doing this wrong ??
My logincontroller
is like this:
public function __construct() { $this->middleware('guest'); } public function login(Request $request) { $validatedData = $request->validate([ 'email' => 'required|email|max:255', 'password' => 'required|max:255', ]); try { $response = HelperFunctions::fetchData('post', 'login/login', [ 'loginId' => $request->get('email'), 'password' => md5($request->get('password')) ]); if ($response['code'] == 200 && $response['success']) { session([ 'api_token' => $response['sessionId'], 'user_data' => $response['data']['profile'] ]); return redirect()->intended(route('home')); } else { return redirect()->back()->with('error', 'Please provide valid credentials'); } } catch (Exception $e) { return redirect()->back()->with('error', 'Opps!! Something is wrong. We are trying to fix it'); }
My authentication checking middleware
class checkAuthentication { /** * Handle an incoming request. * * @param IlluminateHttpRequest $request * @param Closure $next * @return mixed */ public function handle($request, Closure $next) { //check if user is logged in if(Session::has('api_token') && Session::has('user_data')) { return $next($request); } return redirect(route('login')); } }
I also tried to dd()
Session::get('url.intended')
but it returns empty .
I did tried looking for reference on google, laracast & stackoverflow i found some reference , but those did not help me. Can anyone please help me thank you.
Some of the reference i have checked & tried:
- https://laracasts.com/discuss/channels/laravel/redirect-intended-not-working-after-login?page=1
- Laravel 5 – redirect()->intended() after authentication not going to intended
- https://laravel.io/forum/11-24-2014-problems-with-redirectintended-and-auth
Advertisement
Answer
The simplest way would be to redirect()->guest()
in your Auth
middleware instead of the redirect you currently have:
return redirect()->guest(route('login'));
Using the guest()
method on the redirector is what adds the url.intended
value to the session.
Alternatively, instead of returning from the middleware if they’re not authenticated you could throw an AuthenticationException
:
public function handle($request, Closure $next) { //check if user is logged in if(Session::has('api_token') && Session::has('user_data')) { return $next($request); } throw new AuthenticationException('Unauthenticated.'); }
This will allow you to take advantage of Laravel’s ExceptionHandler
if you need to. You will also need to add use IlluminateAuthAuthenticationException;
to the top of your class.