Sometimes we need to create custom validation with a custom message. You can use this to create your custom validation.
- I do prefer Custom Request Page for laravel request handling. you need to write —
$ php artisan make:request CustomStoreRequest
- Then you will get a Request page on
app/Http/Request Folder/CustomStoreRequest.php
Then make the return true to your authorize() method
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.');
}
},
],
];
}
Here you can get data from request via "$this->input('pqr')" or you can validate "$value" for that single value.
- 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.']);
}
Top comments (0)