Search code examples
phplaravellaravel-validation

Laravel how to validate if exists and belong to user


I need to check if the shift_id in the request exists in the database, which can be done by the following

'shift_id' => 'required|exists:shifts,id'

but how can I also check if this shift_id belongs to the authenticated user

notice that the shifts table has a column named user_id


Solution

  • You can use inline validation by adding the name and value of the column after your first column check Like,

    'shift_id' => 'required|exists:shifts,id,user_id,'.auth()->user()->id,
    

    And If you would like to customize the query executed by the validation rule, you may use the Rule class to define the rule fluently. In this example,

    use Illuminate\Support\Facades\Validator;
    use Illuminate\Validation\Rule;
     
    Validator::make($data, [
        'shift_id' => [
             'required',
              Rule::exists('shifts')->where(function ($query) {
                    return $query->where('id', request()->get('shift_id'))->where('user_id', auth()->user()->id);
              }),
         ],
    ]);