laravellaravel-9laravel-validation

Check if an UUID exists in Table A or Table B using Validation Rules (Laravel Validation)?


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.


Solution

  • you can create custom validation rule using php artisan make:rule ticketNumberIsNotUsed

    class TicketNumberIsNotUsed implements Rule
    {
      public function __construct(protected array $tables = [])
      {}
    
      public function passes($attribute, $value)
      {
        // Check if the UUID exists in either of the tables
        foreach ($this->tables as $table => $field) {
          if (DB::table($table)->where($field, $value)->exists()) {
            return true;
          }
        }
    
        return false;
      }
    ...
    
    use App\Rules\TicketNumberIsNotUsed;
    
    $request->validate([
       'uuid' => ['required', new TicketNumberIsNotUsed([
         // list of table => field to search in order
         'courses' => 'course_id',
         'contingents' => 'contingent_id',
        ])],
    ]);