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
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.
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.
If you want to redirect back to a specific page, pass the URL or route in
redirect()