Skip to content
On this page

An image

ray.so

Extend Laravel Validator Morph Exists

A laravel validator extends validator with morph_exists.

Useful validator extend morph_exists.

Put the following on app/Http/Providers/AppServiceProvider.php at boot method.

php
Validator::extend('morph_exists', function ($attribute, $value, $parameters, $validator)
{
  if (!objectType = Arr::get($validator->getData(), $parameters[0], false)) {
    return false;
  }
  // The models namespace.
  return !empty(resolve('App\\Models\\'.$objectType)->find($value));
});

Usage on any validator rules or FormRequest.

php
public function rules()
{
  return [
    'commentable_id' => ['required', 'morph_exists:commentable_type'],
    'commentable_type' => ['required', 'string'],
  ];
}

Last updated: