After authentication, Laravel takes you back to the homepage by default. But in some cases, this is a behavior you want to change. Laravel allows you to take the user where they originally intended to go after they finished authenticating.
First you have to create your custom middleware in app/Http/Middleware
use Illuminate\Support\Facades\Auth;
use Closure;
class IsCustomAuth{
public function handle($request, Closure $next) {
if (Auth::user()) {
return $next($request);
}
return redirect()->guest('/login');
}
}
You have to register your custom middleware in app/Http/kernel.php !
protected $routeMiddleware = [
...
'customAuth' => \App\Http\Middleware\IsCustomAuth::class,
];
Then you need to make a change to app/Http/Middleware/RedirectIfAuthenticated.php :
add ->intended('/') to the redirect() function. '/' being a default fallback uri when the intended destination is not available.
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class RedirectIfAuthenticated
{
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
return redirect()->intended('/');
}
return $next($request);
}
}
Voilà ! After they log in, users will be taken to the destination they originally intended when they clicked the link.
Laravel authentication Redirect