dongya6395 2016-04-24 15:01
浏览 51
已采纳

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.

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.

  • 写回答

1条回答 默认 最新

  • dsz1966 2016-04-24 18:46
    关注

    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.
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助