Automatically Validate Requested Data From Model In Laravel

Hello artisan,

In this Laravel tips and tricks tutorial, I will show you how we can automatically validate our model data in the Laravel application. Normally we validate our requested data from the controller, but in this example, I will show you, how we can validate from the model dynamically in the Laravel application.

You know that every model has a boot() method, using that method we can do it. If you know how model events work, you can utilize them and validate our models on creation. Take a look at the following code:

Let's see the example:

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Validator;

class Post extends Model
{
    public static $rules = [
        'title' => 'required|string|max:255',
        'slug' => 'required|string',
        'excerpt' => 'nullable|string|max:160',
        'published_at' => 'nullable|date',
    ];

    public static function boot()
    {
        parent::boot();

        static::creating(function (Post $post) {
            Validator::validate($post->toArray(), static::$rules);
        });
    }
}

 

Read also: Laravel 9 CRUD Example with Vite Vue and Inertia Js

 

Hope it can help you.

 

#laravel #laravel-9x #laravel-tips-and-tricks