我做这样的门:
Gate::define('update-post', function ($user, Post $post) {
return $user->hasAccess(['update-post']) or $user->id == $post->user_id;
});
我检查了我的数据库,它有更新帖子访问权限,用户ID与帖子相同.但我得到了:
This action is unauthorized.
错误.所以我在这里犯了一些错误吗?谢谢.
解决方法:
我在前面开始使用Form Request类data validation时使用类似的问题(例如使用php artisan make:请求UpdateUserRequest).
如果您使用Form Request验证数据,那么首先,检查您是否正确设置了正确的规则以允许它通过.这是在authorize方法中处理的,该方法返回一个布尔值,默认情况下它设置为false:
namespace App\Http\Requests\Users;
use Illuminate\Foundation\Http\FormRequest;
class UpdateUserRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
/**
* By default it returns false, change it to
* something like this if u are checking authentication
*/
return Auth::check(); // <------------------
/**
* You could also use something more granular, like
* a policy rule or an admin validation like this:
* return auth()->user()->isAdmin();
*/
}
public function rules()
{
// your validations...
}
}