在我的 Laravel 項目中,我想通過Request
這樣的方式授權用戶:
<?php
namespace Domain\Contents\Http\Requests\Blog;
use Domain\Contents\Models\Blog\Post;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Gate;
class ReadPostRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
if (request('id') === null) {
abort(403);
}
$post = Post::whereId(request('id'))->first();
return Gate::allows('view-post', $this->user(), $post);
}
// ...
}
但我認為這部分代碼有點亂:
if (request('id') === null) {
abort(403);
}
$post = Post::whereId(request('id'))->first();
是否有更簡單的解決方案來訪問類中的當前Post
模型Request
?
FormRequests 的文檔表明該authorize()
方法支持類型提示。
如果您正在使用路由模型綁定,則只需在帖子中輸入提示:
public function authorize(Post $post)
{
return Gate::allows('view-post', $this->user(), $post);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句