skip to Main Content

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?

2

Answers


  1. So when you are in show route you can shore previous URL in cache or send as param for delete route and after deleting item you can get the URL and back to previous url.

    Login or Signup to reply.
  2. You can use redirect()->back() to take the user back to the page they just came from.

    You can read more about Redirects in Laravel here.

    public function destroy($id)
    {
        // Do your deletion actions here
    
        // Redirect back to the previous page
        return redirect()->back()->with('success', 'Item deleted successfully');
    }
    

    If you want to redirect back to a specific page, pass the URL or route in redirect()

    public function destroy($id)
        {
            // Do your deletion actions here
        
            // Redirect back to a specific page
            return redirect('/path/to/url')->with('success', 'Item deleted successfully');
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search