我已經設置了我的模型策略,並且在我授權控制器操作內的動作時似乎正在工作。Laravel - 從控制器方法授權作品僅
// create action
public function create()
{
$this->authorize('create', BusinessProfile::class);
return view('business-profile.create');
}
創建策略只是返回true或false,並且切換布爾似乎正在工作,因爲我根據它進行了授權。
這符合我的政策設置正確。
但是,我的控制器中無處不在使用authorize
方法,而是嘗試在構造函數中設置中間件。
Laravel文檔顯示此示例。
Route::post('/post', function() {
// The current user may create posts...
})->middleware('can:create,App\Post');
所以,我在我的控制器構造函數中寫了這個。
public function __construct()
{
$this->middleware('auth');
$this->middleware('can:create,BusinessProfile')->only('create');
}
但是,當這樣做時,動作總是未經授權的。
獎金的資料
我繼續寫垃圾代碼在我的政策,以提高語法錯誤,仍然,我得到它告訴我,我的政策是不費一槍在所有未經授權的響應。這可能是因爲我沒有正確註冊我的政策,但如上所述,$this->authorize(...)
按預期工作。
您是否嘗試過cha ('create','create') - > only('create');'to $ this-> middleware('can:create,App \ BusinessProfile') - > only('create' );'。意味着使用BusinessProfile的完整類名和命名空間。 –
如果您可以發佈政策的代碼,這可能會有所幫助。 –
@MIdrees看來你是對的。我實際上做的是將'App \ BusinessProfile'別名爲'BusinessProfile',然後使用'$ this->中間件('can:create,BusinessProfile') - > only('creat e');'我認爲不在Laravel工作。中間件參數必須是完全限定的型號名稱。對於已經創建模型的動作,它必須是url中參數的名稱。也許,你可以發佈這個答案,以便我可以標記它?請儘量徹底。 –