Search code examples
laravellaravel-blade

How to redirect based on the previous routes in laravel


There are two ways to delete a post in my app:

way 1:

urls:

/ -> posts/{post} -> posts/{post}

names:

home -> posts.show -> posts.destroy

way 2:

urls:

/posts -> /posts/{post} -> posts/{post}

names:

posts.index -> posts.show -> posts.destroy

how can redirect the user back to where he came from after deleting? I want him to be redirected to home in way 1 and to my posts in way 2.

I've seen that it could be done using a hidden input field like this:

<input type="hidden" name="redirect" value="home">

These are my routes:

Route::get('/', [PostController::class, 'latestPosts'])->name('home');

Route::middleware('auth')->group(function () {
    Route::resource('/posts', PostController::class);
});

but this won't really work because both ways are using the same blade view show, so should I just create a separate view for each one of them or is there a better way to do so?


Solution

  • I have faced this similar situation in my own project a few months ago. So I will suggest you to track the user navigation persistently through session to track the URL-state.

    Follow these steps.

    Step 1 :-

    For for / URL, set this session(['redirect_url' => 'index']); to the respected controller method.

    And for /post URL , set this session(['redirect_url' => 'post']); to the respected controller method.

    Step 2 :-

    Then you can set the redirect-url in hidden input field of the form like this.

        @if (session('redirect_url') == "index")
            <input type="hidden" name="redirect" value="index">
        @elseif (session('redirect_url') == "post")
            <input type="hidden" name="redirect" value="post">
        @endif
    

    Step 3 :- Finally ,you can get the redirect_url value by the two ways.

    1. by accessing the input hidden field of the form.
    2. by directly accessing the session-value

    It is demo to retrieve the session value by directly accessing it.

    Get the session-value in the posts/{post}(named posts.destroy) controller method and redirect the user with the following logic.

    if(session('redirect_url') == "index")
    {
      return redirect('/')->with('success', 'Deletion completed 
      successfully'); //redirected to `home`
    }
    elseif(session('redirect_url') == "post")
    {
       return redirect('/posts')->with('success', 'Deletion completed 
       successfully'); //redirected to `posts.index`
    }
    

    Try this, it will work for sure.