【问题标题】:Laravel - Implicit route model binding with soft deleted dataLaravel - 与软删除数据的隐式路由模型绑定
【发布时间】:2023-03-20 09:20:01
【问题描述】:

我遇到了一个小问题。有两种用户角色,一种是普通成员,一种是管理员。成员可以删除博客,删除(软删除)后将无法看到该博客,而管理员仍然可以看到该博客,即使该博客已被软删除。

示例代码:

// 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
}

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

我的RouteServiceProvider

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

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

编辑:当我转储并死去Auth::user() 时,它给了我一个null 值。

非常感谢任何帮助。

【问题讨论】:

  • “它不让我”是什么意思?错误信息,...?
  • 抱歉,我更新了问题。但它只是说 null 并说无法检查 null 上的函数..

标签: php laravel routes laravel-5.2


【解决方案1】:

我刚刚发现在路由服务提供者中获取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.
}

【讨论】:

    猜你喜欢
    • 2013-10-27
    • 2017-01-12
    • 2019-01-10
    • 2017-01-04
    • 2020-05-05
    • 1970-01-01
    • 2016-06-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多