簡體   English   中英

Laravel - 隱式路由 model 與軟刪除數據綁定

[英]Laravel - Implicit route model binding with soft deleted data

我有一個小問題。 有兩種用戶角色,一種是普通會員,一種是管理員。 成員可以刪除博客,刪除(軟刪除)后他們將看不到博客,而管理員仍然可以看到博客,即使是軟刪除。

示例代碼:

// 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() function 來獲取登錄用戶,因此我可以檢查他們是否有權限。

我的RouteServiceProvider

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

這不起作用,因為它不知道Auth::user()是什么。 我已經導入了Auth facade,但仍然無法正常工作。

編輯:當我轉儲並死掉Auth::user()時,它給了我一個null值。

非常感謝任何幫助。

當谷歌搜索這個問題時彈出這個問題,在較新的 Laravel 版本中你可以這樣做:

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

請參閱: 隱式軟刪除模型

我剛剛發現在Route Service Provider中無法獲取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.
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM