'Laravel - Implicit route model binding with soft deleted data
I am having a small issue. There are two user roles and one is a normal member and one is an admin. The member can delete a blog and they will not be able to see the blog after they delete (soft delete) it while the admin can still see the blog, even if it's soft deleted.
Example code:
// Route file
Route::get('/blog/{blog}', 'BlogController@show');
// BlogController
public function show(App\Blog $blog) {
// It never gets to here if the blog has been soft deleted...
// Automatically throws an 404 exception
}
I want the admin to be able to visit the blog even if it's soft deleted but it doesn't really work. I am trying to edit the route service provider but I haven't gotten any luck as it doesn't let me use the Auth::user()
function to get the logged in user so I can check if they have permission.
My RouteServiceProvider
$router->bind('post', function($post) {
if (Auth::user()->isAdmin()
return Post::withTrashed()->where('id', $post)->firstOrFail();
});
This does not work as it doesn't know what Auth::user()
is. I have imported Auth
facade but still doesn't work.
Edit: It gives me a null
value when I dump and die Auth::user()
.
Any help is highly appreciated.
Solution 1:[1]
I just found out that getting the current logged in user
is not possible in Route Service Provider because it loads before all session service provider.
Instead I simply did:
//Route Service Provider
$router->bind('post', function($post)
return Post::withTrashed()->where('id', $post)->firstOrFail();
});
// Controller
public function show(Post $post) {
// If the post has been trashed and the user is not admin, he cannot see it
if (!Auth::user()->isAdmin() && $post->trashed())
abort(404);
// Proceed with normal request because the post has not been deleted.
}
Solution 2:[2]
As this question pop ups when googling for this, in newer Laravel versions you can do this:
Route::get('posts/{post}', [PostController::class, 'show'])->withTrashed();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Taylor |
Solution 2 | dvdheiden |