skip to Main Content

In my Laravel application, I would like to check wether the value of the field uuid is present in table courses or in table contingents using validation rules. The UUID must be present in one of the two tables to proceed. Laravel requires the UUID to be present in both tables, when I’m applying the following ruleset:

$request->validate([
   'uuid' => 'exists:courses,course_id',
   'uuid' => 'exists:contingents,contingent_id
]);

Some kind of “differentiation logic” is required. It would be possible to achieve it with some if statements, but that wouldn’t be a very clean way to solve the problem, I guess.

How can I tell Laravel that the UUID only needs to exist in ONE table for validation to be ok?

Thanks in advance.

2

Answers


  1. use IlluminateSupportFacadesDB;    
    
    $request->validate([
        'uuid' => [
            'required',
            function ($attribute, $value, $fail) {
                $courseExists = DB::table('courses')->where('course_id', $value)->exists();
                $contingentExists = DB::table('contingents')->where('contingent_id', $value)->exists();
    
                if (!$courseExists && !$contingentExists) {
                    $fail('The :attribute must exist in either the courses or contingents table.');
                }
            },
        ],
    ]);
    
    Login or Signup to reply.
  2. you can use custom validation rule
    first of all make new rule using php artisan make:rule ruleName.
    now write this function in the rule class

    public function passes($attribute, $value)
    {
        // Check if the UUID exists in either courses or contingents table
        $existsInCourses = DB::table('courses')->where('course_id', $value)->exists();
        $existsInContingents = DB::table('contingents')->where('contingent_id', $value)->exists();
    
        return $existsInCourses || $existsInContingents;
    }
    

    after that use it in your controller like that

    use AppRulesRuleName;
    
    // Inside your controller method
    $request->validate([
       'uuid' => ['required', new RuleName],
    ]);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search