Laravel-带有软删除数据的隐式路由模型绑定 [英] Laravel - Implicit route model binding with soft deleted data

查看:203
本文介绍了Laravel-带有软删除数据的隐式路由模型绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

示例代码:

// 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()函数来获取登录用户,因此我可以检查他们是否具有权限.

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.

我的RouteServiceProvider

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

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

This does not work as it doesn't know what Auth::user() is. I have imported Auth facade but still doesn't work.

当我转储并消亡Auth::user()时,它给了我一个null值.

It gives me a null value when I dump and die Auth::user().

我们非常感谢您的帮助.

Any help is highly appreciated.

推荐答案

我刚刚发现,在路由服务提供程序中无法获取current logged in user,因为它会在所有会话服务提供程序之前加载.

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

这篇关于Laravel-带有软删除数据的隐式路由模型绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆