DEV Community

Cover image for Laravel Custom Validation
Arman Rahman
Arman Rahman

Posted on • Edited on

1

Laravel Custom Validation

Sometimes we need to create custom validation with a custom message. You can use this to create your custom validation.

  1. I do prefer Custom Request Page for laravel request handling. you need to write —
$ php artisan make:request CustomStoreRequest
Enter fullscreen mode Exit fullscreen mode
  1. Then you will get a Request page on

app/Http/Request Folder/CustomStoreRequest.php

  1. Then make the return true to your authorize() method

  2. apply your custom condition like this

public function rules()
    {
        return [
            'xyz' => 'required',
            'pqr' => [
                'nullable',
                function ($attribute, $value, $fail) {
                    $PQR = $this->input('pqr');
                    $XYZ = $this->input('xyz');
                    if ($PQR === $XYZ) {
                        $fail('Message on error.');
                    }
                    if ($value === 'admin@example.com') {
                        $fail('The provided email address is not allowed.');
                }
                },
            ],
        ];
    }
Enter fullscreen mode Exit fullscreen mode

Here you can get data from request via "$this->input('pqr')" or you can validate "$value" for that single value.

  1. Now add this "CustomStoreRequest" to your Controller Request Parameter -
//use namespace on top
use App\Http\Requests\Category\CustomStoreRequest;

    public function update(CustomStoreRequest $request, $id)
    {
        $Category = Category::findOrFail($id);
        $Category->xyz = xyz;
        $Category->pqr = $request->pqr;
        $Category->save();

        return response()->json(['response'=>'success', 'message'=>'Category Updated Successfully.']);
    }
Enter fullscreen mode Exit fullscreen mode

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs