在我的 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?
uj5u.com熱心網友回復:
FormRequests 的檔案表明該authorize()方法支持型別提示。
如果您正在使用路由模型系結,則只需在帖子中輸入提示:
public function authorize(Post $post)
{
return Gate::allows('view-post', $this->user(), $post);
}
uj5u.com熱心網友回復:
替代解決方案是您可以直接訪問與模型系結一起使用的模型。
return Gate::allows('view-post', $this->user(), $this->post);
為了便于使用,您可以在評論中鍵入提示。
/**
* @property \App\Models\Post $post
*/
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/364643.html
