DEV Community

Cover image for Laravel Custom Validation
Arman Rahman
Arman Rahman

Posted on • Updated on

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

Top comments (0)