How to Create Custom Validation Rules In Laravel

How to Create Custom Validation Rules In Laravel

This tutorial will explain to you, how to create custom validation in laravel.

In the very first step run a “php artisan” command for creating a file in the Rules folder.

Also Read: Image Validation Using Javascript

Now, let’s create a validation rule that can check the company name (which is concatenate with underscore) exists in database table:

Let’s run a command:

php artisan make:rule CompanyNameExists

Laravel generates a file app/Rules/CompanyNameExists.php:

namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
 
class CompanyNameExists implements Rule
{
	/**
	* Determine if the validation rule passes.
	*
	* @param  string  $attribute
	* @param  mixed  $value
	* @return bool
	*/
	
	public function __construct() {}
	public function passes($attribute, $value)
	{
		//
	}
	
	/**
	* Get the validation error message.
	*
	* @return string
	*/
	
	public function message()
	{
		return 'The validation error message.';
	}
}

As I said, it’s similar to Requests classes for validation. We fill in the methods. passes() should return true/false depending on $value condition, which is this in our case:

public function passes($attribute, $value)
{
	$model = 'App\Models\TableName'; //Define Model For Query
	$value = str_replace('_', '', $value);
	Return $model::where('fieldname',$value)->count() > 0; //Define your logic here
}

Next, we fill in the error message to be this:

public function message()
{
    return 'Company Name is not found'; //Define Your Error Message Here
}

Define your rule name in the controller to be this:

use App\Rules\CompanyNameExists;

Finally, how we use this class? In controller’s YourMethod() method we have this code:

$rules['fieldname'] = ['required', new CompanyNameExists];

Full code of custom validation rule file:

<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;

class CompanyNameExists implements Rule
{
    /**
     * Create a new rule instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        $model =  'App\Models\Company';
        $value = str_replace('_', ' ', $value);
        return $model::where('name',$value)->count() > 0;
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'Company Name is not found!';
    }
}

Full code of controller file:

<?php 
use App\Http\Controllers\Controller;
use App\Rules\CompanyNameExists;

class CompanyController extends Controller
{

	public function companySubmit(Request $request){		
		try{
			$rules['fieldname'] = ['required',new CompanyNameExists];
			$validator = Validator::make($request->all(),$rules);
			if($validator->fails()){
				$errors = $validator->errors()->all();
				$response=array();
				$response["status"]=0;
				$response["msg"]=$errors[0];
                return response()->json($response);// response as json
            }
            return response()->json($response);// response as json 
        }catch(\Exception $e){
			Log::error('CompanyController-companySubmit: '.$e->getMessage());
			return view('error.home');
		}
	}
}
About Author

Hey, this is Nilesh Sharma and I belong to the Pink City (Jaipur). My job as a software developer has made me a patient man and negotiation my skills! My job also keeps me on my toes, as i always trying to learn new skills to keep pace with the changing technology landscape.

Sign up for weekly update

Milkshake is almost ready. If you're interested in testing it out, then sign up below to get exclusive access.