如何验证 Laravel 中的请求用户?

How can I validate the request user in Laravel?

我正在发送更新请求,例如:

Route::put('user/{user}/edit-user-education', 'UpdateUserEducationController@editUserEducation');

我的控制器是:

class UpdateUserEducationController extends Controller
{
    public function editUserEducation(UserEducation $education, User $user, EditUserEducationRequest $request)
    {
        $education->school = $request->school;
        $education->degree = $request->degree;
        $education->user_id = $user->id;  // here to validate

  
        $education->save();

        return response()->json([
            'message' => 'Education Updated'
        ]);
    }
}

现在我如何使用已经插入到数据库中的 user_id 来验证请求 user_id?我想确保只有一个用户可以更新创建该记录的用户。

如何操作?提前致谢

在此处查看有关验证的文档: https://laravel.com/docs/8.x/validation

具体来说,我认为您需要 exists 规则: https://laravel.com/docs/8.x/validation#rule-exists

快速而肮脏的方法是在控制器中添加验证,但如文档中所述,还有一些更好的方法。我通常选择表单请求,看起来你已经完成了,因为你的请求是 EditUserEducationRequest.

的一个实例

在控制器中你可以添加:

$validated = $EditUserEducationRequest->validate([
    'user_id' => 'required|exists:users',
]);

我假设您的用户 table 叫做 users

您也可以根据文档在表单请求的 rules 数组中声明 user_idexists 验证规则。

编辑:

其实我在你原来的post中漏掉了一个要求,那就是发送请求的用户必须和被更新的用户是同一个用户。 这可以在您的表单请求的 authorize 方法中处理,例如:

public function authorize()
{
    return $this->user()->id == $this->user_id;
}

只需检查当前用户是否与尝试更新记录的用户相同。

class UpdateUserEducationController extends Controller
{
    public function editUserEducation(UserEducation $education, User $user, EditUserEducationRequest $request)
    {
        if($user->id==Auth::user()->id){
            $education->school = $request->school;
            $education->degree = $request->degree;
            $education->user_id = $user->id;  // here to validate

  
            $education->save();

            return response()->json([
                'message' => 'Education Updated'
            ]);
        }
        else{
            return response()->json([
                'error' => 'Invalid User'
            ]);
        } 
    }
}