Laravel 8 Auth Redirection Using redirectTo | Techiediaries

For laravel 5.0 (only what is different)

You should register your route like this:

How to redirect back to original url after successful login in laravel

You’ve set up your new Laravel 8 project and installed the laravel/ui composer package. Moreover, you’ve added the auth boilerplate along with the vue or react preset and migrated the required database tables for your auth system.

You are ready to start building your project’s functionality but would like to set the authentication up in such way, so that your users are redirected back to the page they were before trying to sign in. How would that work?

If you have added the auth middleware to protect specific routes in your routes/web.php, then your users will be redirected to the login page if they try to access them. In that case, they will be redirected back to the intended page automatically after successful authentication.

Now, let’s say we have a publicly available blog page and we also link to the login form in that page. How can we set up the auth system in such way, so that they are redirected back to our blog page after successful authentication? The solution is easy if we take advantage of the feature already implemented by default.

Laravel uses the url.intented key to store the url of the intended page in the session, so it automatically knows where to redirect after login. This only works though, when we try to access a protected page and we are automatically redirected to the login.

Похожее:  Настройка мобильного приложения Pandora/Pandect | ProService

To make it work even when we just link to the login page, we will have to make few changes to the original code in the following files.

/* app/Http/Middleware/RedirectIfAuthenticated.php */

  * Handle an incoming request.
  * @param  IlluminateHttpRequest  $request
  * @param  Closure  $next
  * @param  string|null  $guard
  * @return mixed
public function handle($request, Closure $next, $guard = null)
    if (Auth::guard($guard)->check()) {
        return redirect()->intended('/');
    return $next($request);

After that change, the users will always be redirected to the url saved in the url.intented session key if it is set.

/* app/Http/Controllers/Auth/LoginController.php */

  * Show the application's login form.
  * @return IlluminateHttpResponse
public function showLoginForm()
    // Get URLs
    $urlPrevious = url()->previous();
    $urlBase = url()->to('/');
    // Set the previous url that we came from to redirect to after successful login but only if is internal
    if(($urlPrevious != $urlBase . '/login') && (substr($urlPrevious, 0, strlen($urlBase)) === $urlBase)) {
        session()->put('url.intended', $urlPrevious);
    return view('auth.login');

We will have to add the previous function in the LoginController class which will basically override the default one from the auth preset which just returns the auth.login view.

What it does, is to always store the previous url page in the session if the previous page is from our website but not the login page itself. Now, we can link to the login route from any other page we want and have the auth system redirect users back to the original page after successful login.

That’s all it takes to implement such functionality! I hope that this Laravel tip is helpful. Be sure to stay tuned for more in the future.

Как в laravel 8 сделать переадресацию на другую страницу сразу после авторизации?

В RouteServiceProvider написал public const HOME = '/welcome'; Но сюда направляет, только если пользователь не аунтифицирован. А мне нужно направлять сюда сразу после регистрации или авторизации (сейчас перенаправляет в корневую директорию “/”.

Похожее:  Льготы и привилегии - Служба крови

Не пойму уже куда копать?

1 Звезда2 Звезды3 Звезды4 Звезды5 Звезд (1 оценок, среднее: 4,00 из 5)

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *