Skip to content

Instantly share code, notes, and snippets.

@nickpoulos
Last active September 6, 2019 03:53
Show Gist options
  • Save nickpoulos/e95c6cf2ddbcdac7542024a3ed921ef2 to your computer and use it in GitHub Desktop.
Save nickpoulos/e95c6cf2ddbcdac7542024a3ed921ef2 to your computer and use it in GitHub Desktop.
Laravel Validator Extension For Morphable Relations (ex. An exists rule for multiple conditions)
use Illuminate\Support\Arr;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Support\Facades\Validator;
Validator::extend('poly_exists', function ($attribute, $value, $parameters, $validator) {
// usage:
// 'commentable_id' => 'required|poly_exists:commentable_type
if (! $type = Arr:get($validator->getData(), $parameters[0], false)) {
return false;
}
if (Relation::getMorphedModel($type)) {
$type = Relation::getMorphedModel($type);
}
if (! class_exists($type)) {
return false;
}
return ! empty(resolve($type)->find($value));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment