Search code examples
laravellaravel-livewire

How in laravel with two routes under same middleware, after auth goes to their route?


This is my Route:

Route::middleware(['auth'])->group(function () {
    Route::get('/add', Add::class)->name('add');
    Route::get('/profile/{user}', Profile::class)->name('profile');
});

and the view has two links:

<a href="{{ route('add') }}">Add</a>
<a href="{{ route('profile', auth()->id()) }}">profile</a>

in the guest state, both links go to the login page, I want after login each route to be redirected to its destination automatically, something like this in the Login Auth function:

if request()->route or URL has "add"

return redirect()->to_route('add')

or something with another middleware.

?


Solution

  • use Laravel redirects intended method. Using the intended method after successful login it will redirect to the last page . if the user directly login then it goes to a specified route (here its the dashboard)

    if(Auth::attempt(["email" => "", "password" =>""])){
                    
       return redirect()->intended('dashboard');
    }
    

    The intended method provided by Laravel's redirector will redirect the user to the URL they were attempting to access before being intercepted by the authentication middleware. A fallback URI may be given to this method in case the intended destination is not available.

    Ref :https://laravel.com/docs/10.x/authentication#authenticating-users