Question: Laravel 5.3 Validation: Unique period time which is set by two column (start_date, end_date)

Question

Laravel 5.3 Validation: Unique period time which is set by two column (start_date, end_date)

Answers 1
Added at 2016-12-27 08:12
Tags
Question

Is there any way to validate the unique period times which is set by two column (start_date, end_date)? Please let me know if this is possible by using Laravel 5.3 validator.

Thanks Arvi

Answers
nr: #1 dodano: 2016-12-27 12:12

So far as I know there is no way to accomplish such complex custom rules on Laravel. I understand that you really wanna do some thing like this:

//////////////////////////////////////////////////
// This is not working code. just an idea !!!
//
$data['period'] = $data['start_date'] . "-" . $data['end_date'];
        $validator = Validator::make($data, [    
            'period' => Rule::unique('projects', DB::raw('concat(start_date, "-", end_date)')),
        ], [
            'period' => 'Period is duplicated.',
        ]);

But Larvel does not accept this kind of rule (actually I am wondering why they do not accept this kind of approach)

So you have 2 options.

Solution 1. Create a view in the database, which will have additional column "period" which is made by concat(start_date,"-",end_date). And then make the code like following.

$data['period'] = $data['start_date'] . "-" . $data['end_date'];
        $validator = Validator::make($data, [    
            'period' => Rule::unique('projects', DB::raw('concat(start_date, "-", end_date)')),
        ], [
            'period' => 'Period is duplicated.',
        ]);

if ($validator->fails()) {
  // do some thing
} else {
  unset($data['period']); // When adding or update, 'period' will cause error because period is only in view, not in table itself
  // do insert or update
}

Solution 2. Just pass normal validation except for the unique checking, after all validation done, you do checking yourself by searching in the table manually. Like following:

if (Project::where(DB::raw("concat(start_date, '-', end_date)"), "=", $data['start_date'] . "-" . $data['end_date'])->count() > 0) {
  // now this is not unique, so do something
}
Source Show
◀ Wstecz