How to write custom validation rule in controller Laravel?

You can define your custom validator inside AppServiceProvider like this:

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Validator;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Validator::extend('phone_unique', function ($attribute, $value, $parameters, $validator) {
          $inputs = $validator->getData();
          $code = $inputs['code'];
          $phone = $inputs['phone'];
          $concatenated_number = $code . ' ' . $phone;
          $except_id = (!empty($parameters)) ? head($parameters) : null;

          $query = User::where('phone', $concatenated_number);
          if(!empty($except_id)) {
            $query->where('id', '<>', $except);
          }

          return $query->exists();
      });

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

You can get all the inputs passed to the validator, by accessing $validator property - getData()

You can just add an extra parameter to your rules array after your custom validation rule (just after the colon) like this:

'phone' => 'required|phone_unique:1',

Pass the id to be ignored while checking entries into the db

The custom validator Closure receives four arguments: the name of the $attribute being validated, the $value of the attribute, an array of $parameters passed to the rule, and the Validator instance.

Now you can call the validator like this:

$validator = Validator::make($request->all(), [
      'email' => 'required|email',
      'code' => 'required|string|min:3|max:4',
      'phone' => 'required|phone_unique:1',
      'timezone' => 'required|numeric',
      'country' => 'required|integer',
      'agreement' => 'accepted'
  ], [
    'phone_unique' => 'Phone already exists!', // <---- pass a message for your custom validator
  ]);

See more about Custom Validation Rules.


$messsages = array(
        'email.required'=>'Email is Required',
        'phone.required'=>'Phone number is Required',

    );

    $rules = array(
        'email' => 'required',
        'phone' => 'required',

    );

    $validator = Validator::make(Input::all(), $rules,$messsages);



    if ($validator->fails()):
        $this->throwValidationException($request, $validator);
    endif;

I am writing this answer because I believe bunch of people are looking for some good answer for this topic. So I decided to share my code that I am using for booking site, where I want to check that IS NOT arrival_date > departure_date.

My version of Laravel is 5.3.30

public function postSolitudeStepTwo(Request $request)
{
    $rules = [
        'arrival_date' => 'required|date',
        'departure_date' => 'required|departure_date_check',
        'occasional_accompaniment_requested' => 'required|integer',
        'accommodation' => 'required|integer',
        'are_you_visiting_director' => 'required|integer',
    ];

    if ($request->input('are_you_visiting_director') == 1) {
        $rules['time_in_lieu'] = 'required|integer';
    }

    $messages = [
        'departure_date_check' => 'Departure date can\'t be smaller then Arrival date.Please check your dates.'
    ];

    $validation = validator(
        $request->toArray(),
        $rules,
        $messages
    );

    //If validation fail send back the Input with errors
    if($validation->fails()) {
        //withInput keep the users info
        return redirect()->back()->withInput()->withErrors($validation->messages());
    } else {
        MySession::setSessionData('arrival_date', $request);
        MySession::setSessionData('departure_date', $request);
        MySession::setSessionData('occasional_accompaniment_requested', $request);
        MySession::setSessionData('accommodation', $request);
        MySession::setSessionData('are_you_visiting_director', $request);
        MySession::setSessionData('time_in_lieu', $request);
        MySession::setSessionData('comment_solitude_step2_1', $request);

        //return $request->session()->all();
        return redirect("/getSolitudeStepThree");
    }
}

My controller is StepController and there I have declared a method as you can see called postSolitudeStepTwo. I declare the rules and on departure date notice that for the rule we have required|departure_date_check. That will be the name of the method in

app/Providers/AppServiceProvider.php

The code there looks like this:

public function boot()
{
    Validator::extend('departure_date_check', function ($attribute, $value, $parameters, $validator) {
        $inputs = $validator->getData();
        $arrivalDate = $inputs['arrival_date'];
        $departureDate = $inputs['departure_date'];
        $result = true;
        if ($arrivalDate > $departureDate) {
            $result = false;
        }
        return $result;
    });
}

As the Laravel documentation 5.3 Custom validation rules we need to extend the Validator facade, the signature of that method has to be:

Validator::extend(name_of_the_function, function ($attribute, $value, $parameters, $validator) {

And I believe the rest is clear.

Hope it will help somebody.

Cutom Validation error frontend