Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom error code for laravel form request

I have an endpoint I would like to post a bulk update request like this:

{
   "resources": [
      {
         "id": 5,
         "name": "ABC"
      }
   ]
}

I am trying to prevent someone updating a resource they are not the owner of. I can create the following rule to prevent this:

'resources.*.id' => ['required', 'exists:resources,id,team_id,' . $this->team()->id],

I'd like to customize the error code so that I receive a 403 error code when this rule is violated. All other rules I am happy with the normal 422 error code.

I am aware I can customize the message in the messages() method. Is there something similar so I can return my own error code? At the moment I just get the standard 422 code.

I am also aware I could load all the team resources in the authorize() method, but I wonder if there is a better way?

Thanks.

like image 827
reans Avatar asked Jun 14 '26 16:06

reans


1 Answers

Maybe I'm a bit late, but hopefully, my answer can still help you or someone in the future.

You can see the Form Request Validation Class you created extends from Illuminate\Foundation\Http\FormRequest. Then if you look at the source code on the Laravel Framework, there is a function to handle failed validation attempts.

So the solution, you can override the default failedValidation function in the Form Request Validation Class you created. Here is a sample code you can use:

// ./app/Http/Requests/UpdateFooBarRequest.php

...
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Response;
use Illuminate\Validation\ValidationException;

class UpdateFooBarRequest extends FormRequest
{
    ...

    /**
     * Handle a failed validation attempt.
     *
     * @param  \Illuminate\Contracts\Validation\Validator  $validator
     * @return void
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    protected function failedValidation(Validator $validator)
    {
        throw (new ValidationException($validator))
                    ->errorBag($this->errorBag)
                    ->redirectTo($this->getRedirectUrl())
                    ->status(Response::HTTP_FORBIDDEN);
    }
}

Credit: Discussion from Laracasts - How to make a custom FormRequest error response in Laravel 5.5

like image 199
Yusuf T. Avatar answered Jun 16 '26 07:06

Yusuf T.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!