How To Add After Validation Hook In Laravel Example

  • 26-09-2022
  • 864
  • Laravel 9
  • Haresh Chauhan

How To Add After Validation Hook In Laravel Example; in This post I will show you how how to add a validation hook after successfully passing given validation all rules. Sometimes developers need to add after validation hook when they try to make their custom validation extended rule in the post request.

Adding Custom Rule to After Validation Hook after validation; We will see the "after validation hook" add-in controller and request class. This is important while you want to check extra validation apart from the given framework validation and want to check some logical condition in the post request that time this validation hook will help you to make to validate.

Example 1

See below given example, You can also attach a callback after the validation is completed. This will be allowing you to perform further validation rule add action once the core validation is a success. This will add the same validation array message collection.

use App\Models\SubCategory;

public function store(Request $request)
{
    $validated = \Validator::make($request->all(),[
        'name' => 'required|max:250',
        'category_id' => 'required|integer|exists:categories,id',
        'feature' => 'nullable',
        'gender' => 'nullable',
        'status' => 'required|in:1,2',
        'price' => 'required|numeric',
        'cost' => 'required|numeric',
    ]);

    $validated->after(function($validated) use ($request){
        
        if (SubCategory::where('name',$request->name)
            ->where('gender',$request->gender)
            ->where('category_id',$request->category_id)->exists()){
            
            $validated->errors()->add('name', 'The Category name already exists!');
        }
    });

    if ($validated->fails()){

        return redirect()
            ->route('subcategory.create')
            ->withInput($validated->validated())
            ->withErrors($validated->errors());
    }

    $validated = $validated->validated();

    SubCategory::create($validated);
}

Example 2. Adding After Hooks To Form Requests

Request call adds after hook validation. If you are using the request class for the validation. you may use the withValidator method. This somehow will receive the full construction of the validator. This allows you to call any of its methods before the validation rules are evaluated.

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class TestRequest extends FormRequest
{
    /**
        * Determine if the user is authorized to make this request.
        *
        * @return bool
        */
    public function authorize()
    {
        return true;
    }

    /**
        * Get the validation rules that apply to the request.
        *
        * @return array
        */
    public function rules()
    {
        return [
            'name' => 'required'
        ];
    }

    public function withValidator($validator)
    {
        $validator->after(function ($validator) {
            if ($this->somethingElseIsInvalid()) {
                $validator->errors()->add('name', 'Something is wrong with this field!');
            }
        });
    }
}

Custom Validation Message Laravel


We always thanks to you for reading our blogs.


dharmesh-image

Dharmesh Chauhan

(Swapinfoway Founder)

Hello Sir, We are brothers origin from Gujarat India, Fullstack developers working together since 2016. We have lots of skills in web development in different technologies here I mention PHP, Laravel, Javascript, Vuejs, Ajax, API, Payment Gateway Integration, Database, HTML5, CSS3, and Server Administration. So you need our service Please Contact Us

haresh-image

Haresh Chauhan

(Co-Founder)


We Are Also Recommending You :