Category: Laravel, api

In this blogpost I’m going to show you how to merge validation of 4 different type of requests on the same model into one FormRequest class. The framework provides different ways of dealing with validation, for example by adding the validation rules inside your controller: There is not wrong with this approach.

This is fine for the store method, but for the update method, we need to add the ignore method like this: Rule::unique('posts')->ignore($this->post->id); By the way, the $this->post comes from the controller where $post is type hinted in the updated method signature: So we have to different kind or unique rules for the title field depending on the store or update action.

Luckily we have abstracted our rules, so we can just reuse our form request class in our API controller: This API controller is almost identical as the controller we had before, but the responses from the API controller will be most likely JSON formatted, while the web controller will answer the request with a view.

Most likely your API endpoints are prefixed with api/, so we can use this information to handle API requests inside our form request like this: We now check for an API request inside the prepareForValidation method, and exit early when an API request is detected.
Newsletter

Get the latest Laravel/PHP jobs, events and curated articles straight to your inbox, once a week

Fathom Analytics | Fast, simple and privacy-focused website analytics. Fathom Analytics | Fast, simple and privacy-focused website analytics.
Achieve superior email deliverability with ToastMail! Our AI-driven tool warms up inboxes, monitors reputation, and ensures emails reach their intended destination. Sign up today for a spam-free future. Achieve superior email deliverability with ToastMail! Our AI-driven tool warms up inboxes, monitors reputation, and ensures emails reach their intended destination. Sign up today for a spam-free future.
Community Partners