Laravel applications created using authentication methods will restrict certain pages from being accessed by guests or visitors who have not logged in to the application. By default, Laravel will redirect to the home page after a user successfully authenticates. An example of a scheme like this:
- Someone who wants to visit the nusagates.co.id/profile page but because they are not logged in, they are automatically redirected to the login page.
- After its succeed, Laravel will automatically redirect to the home page.
So how can the person be redirected to the profile page after successfully logging in? The answer is quite concise. We only need to edit a line of code in Middleware.
How to Change Page Redirect Scheme After Login in Laravel
The method is as follows:
- Edit this files
/app/Http/Middleware/RedirectIfAuthenticated.php
- Change this line of code
return redirect(RouteServiceProvider::HOME);
to a returnredirect()->intended(RouteServiceProvider::HOME);
The code changes above are required for Laravel version 5.3 and above which will save the last intended URL when checking Auth Guard.
Model of Complete Laravel Middleware Code RedirectIfAuthenticated.php
<?php
namespace App\Http\Middleware;
use App\Providers\RouteServiceProvider;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class RedirectIfAuthenticated
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
* @param string|null ...$guards
* @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
*/
public function handle(Request $request, Closure $next, ...$guards)
{
$guards = empty($guards) ? [null] : $guards;
foreach ($guards as $guard) {
if (Auth::guard($guard)->check()) {
return redirect()->intended(RouteServiceProvider::HOME);
}
}
return $next($request);
}
}