How to Self Validate Eloquent Model Before Save in Laravel

How to Self Validate Eloquent Model Before Save in Laravel cover image

There are several packages on the web to validate the model, but most of them are not working with newer Laravel versions. That’s why Minute of Laravel created a simple model class as a package for this purpose which is called Laravel Self Validating Model. This package contains an extended Eloquent Model class which self-validates against validation rules specified in the Model’s rules property when the Model is saved/updated.

It works with:

  • Laravel 9
  • Laravel 8
  • Laravel 7
  • Laravel 6

Installation

You can install this package via composer:

composer require minuteoflaravel/laravel-self-validating-model

How to use

Let’s say we have a Contact model which extends Illuminate\Database\Eloquent\Model:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Contact extends Model
{
    use HasFactory;
}

Instead of extending Illuminate\Database\Eloquent\Model we should extend MinuteOfLaravel\Validation\SelfValidatingModel:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use MinuteOfLaravel\Validation\SelfValidatingModel as Model;

class Contact extends Model
{
    use HasFactory;
}

Then just add you validation rules to the $rules property:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use MinuteOfLaravel\Validation\SelfValidatingModel as Model;

class Contact extends Model
{
    use HasFactory;
    
    public $rules = [
        'first_name' => 'required',
        'last_name' => 'required',
        'email' => 'required|email:rfc,dns,spoof',
    ];
}

That’s it! The model will be validated on save/update.

Custom error messages

If you need to add your custom translatable error message then just add it as always to resources/lang/en/validation.php file.

For more details visit Github

Note

Codebrisk is here to deliver you exactly what you may need. We are a dedicated and proven company with considerable experience in the Laravel e-commerce and CRM web development field. We can provide you with custom-made e-commerce web applications with a ton of advanced features and options.

If you want to develop an eCommerce website or CRM system in Laravel, You can send us an email at rizwan@codebrisk.com or get in touch with us, we will get back to you asap.

Written by

Rizwan Aslam

Founder and CEO of CodeBrisk, with years of experience building web applications with Laravel and leading a team of expert developers.

More about Rizwan
Book a free call
Book a call with CodeBrisk