Reputation: 5
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.
Upvotes: 0
Views: 134
Reputation: 17835
route('post.show', $post->slug)
will always evaluate as true
, 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
Route::delete('/post/delete/{id}/{fromList}', ...)->name('post.delete');
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.
<?php
public function delete($id, $fromList){
$post = Post::findOrFail($id);
$post->delete();
if($fromList == '0'){
return redirect()->route('home')->with(["message" => "Your Post has been deleted successfully"]);
}
return back()->with(["message" => "Your Post has been deleted successfully"]);
}
Upvotes: 0
Reputation: 1094
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 value home
.
Then in the controller based on the redirectTo
parameter you can implement your own redirection logic.
{
$post = Post::findOrFail($id);
$post->delete();
$redirectTo = $request->get('redirectTo') ?? "";
if($redirectTo == "home"){
return redirect()->route('home')->with(["message" => "Your Post has been deleted successfully");
} else {
return back()->with(["message" => "Your Post has been deleted successfully");
}
}
Upvotes: 0