Last active
September 6, 2019 03:53
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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