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

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

示例代码

// 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 Facade,但仍然无法正常工作.

编辑:当我转储和死Auth :: 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.
}

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...