Laravel - 与软删除数据的隐式路由模型绑定

Tay*_*lor 6 php routes laravel laravel-5

我有一个小问题。有两种用户角色,一种是普通成员,一种是管理员。成员可以删除博客,并且在删除(软删除)博客后他们将无法看到该博客,而管理员仍然可以看到该博客,即使它是软删除的。

示例代码:

// 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
}
Run Code Online (Sandbox Code Playgroud)

我希望管理员能够访问博客,即使它被软删除,但它实际上不起作用。我正在尝试编辑路线服务提供商,但我没有得到任何运气,因为它不允许我使用该Auth::user()功能来获取登录用户,以便我可以检查他们是否有权限。

我的RouteServiceProvider

  $router->bind('post', function($post) {
        if (Auth::user()->isAdmin()
            return Post::withTrashed()->where('id', $post)->firstOrFail();
    });
Run Code Online (Sandbox Code Playgroud)

这不起作用,因为它不知道Auth::user()是什么。我已经导入了Auth门面,但仍然不起作用。

编辑:null当我转储和死亡时,它给了我一个价值Auth::user()

非常感谢任何帮助。

小智 12

由于在谷歌搜索时会弹出这个问题,在较新的 Laravel 版本中你可以这样做:

Route::get('posts/{post}', [PostController::class, 'show'])->withTrashed();
Run Code Online (Sandbox Code Playgroud)

请参阅:隐式软删除模型


Tay*_*lor 4

我刚刚发现current logged in user在路由服务提供程序中获取 是不可能的,因为它在所有会话服务提供程序之前加载。

相反,我只是简单地做了:

//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.
}
Run Code Online (Sandbox Code Playgroud)