Scenario: A post has a delete button in all posts list view and the postShow view. So if the post is deleted from the list it will return back()->with(‘success’, ‘Some message’) but if we delete it from the postShow view then redirect to the home.
(in short if the the post is deleted via show page then it redirects to home else redirect back)
{
$post = Post::findOrFail($id);
$post->delete();
if(route('post.show', $post->slug)){
return redirect()->route('home')->with(["message" => "Your Post has been deleted successfully");
} else {
return back()->with(["message" => "Your Post has been deleted successfully");
}
}
This is the code but it is always redirecting to home.
3
Answers
In my opinion the simplest way to approach this would be to include a query parameter when you are sending the request from the all posts list view.
From the all posts list view you could add the parameter
redirectTo
with the valuehome
.Then in the controller based on the
redirectTo
parameter you can implement your own redirection logic.route('post.show', $post->slug)
will always evaluate astrue
, isn’t it? Hence it is always redirecting to the home page.Note that the below method is not hack proof, but the task at hand is too trivial to make it hack proof anyway.
In your routes, you can have the route for delete as below with additional parameter of
fromList
In your view files, the delete route link would be,
List page –
route('post.delete',['id' => $yourID, 'fromList' => 1])
Show page –
route('post.delete',['id' => $yourID, 'fromList' => 0])
Then in your controller’s delete method, you can check where to redirect based on the
fromList
flag.The code you provided is not working as expected because the condition
if(route('post.show', $post->slug))
will always evaluate to true. This condition is checking if the route "post.show" with the post’s slug exists, and it will exist as long as you have defined the "post.show" route in your routes file.To achieve the desired behavior of redirecting to the home page if the post is deleted from the "postShow" view and redirecting back otherwise, you can modify your code like this:
In the condition where you check if the post is deleted from the "postShow" view, you should add your logic to determine whether it was deleted from that specific view. If it was deleted from the show page, set the
$isDeletedFromShowPage
variable to true, and then use that variable to determine the redirect behavior.