Skip to content

Instantly share code, notes, and snippets.

@srph
Last active May 8, 2017 07:29
Show Gist options
  • Select an option

  • Save srph/2fb82a881c3223a6907b8ce851ae518e to your computer and use it in GitHub Desktop.

Select an option

Save srph/2fb82a881c3223a6907b8ce851ae518e to your computer and use it in GitHub Desktop.
Laravel: Validation for conflicting schedule
<?php
namespace App\Providers;
use App\Schedule;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Validator;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
/**
* Validation that a block's (class / section) schedules has no overlapping time
*
* @usage Basic usage
* Validator::make($inputs, ['schedule' => "conflict_free_schedule:{$block_id},{$start},{$end}" ]);
*
* @usage Ignore a certain id (when updating)
* Validator::make($inputs, ['schedule' => "conflict_free_schedule:{$block_id},{$start},{$end},{$day},{$schedule_id}" ]);
*/
Validator::extendImplicit('conflict_free_schedule', function($attribute, $value, $parameters, $validator) {
$id = $parameters[0];
$start = $parameters[1];
$end = $parameters[2];
$day = $parameters[3];
$ignore = array_get($parameters, '4');
// http://stackoverflow.com/a/37015643/2698227
$query = Schedule::where('block_id', $id)
->where('start_time', '<', $end)
->where('end_time', '>', $start)
->where('day', $day);
if ($ignore) {
$query->where('id', '!=', $ignore);
}
$conflicting = $query->first();
return null == $conflicting;
});
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
}
<?php
return [
/*
|--------------------------------------------------------------------------
| Custom Validation Language Lines
|--------------------------------------------------------------------------
|
| The following language lines contain the error messages for custom
| validation rules
|
*/
'conflict_free_schedule' => 'The :attribute is conflicting with other schedules',
];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment