Laravel interview question · Most asked
How do you validate requests in Laravel? Why use Form Requests?
Summary
Use $request->validate([...]) for simple cases, or a Form Request class that holds the rules, authorization check and custom messages. On failure Laravel redirects back with errors (web) or returns a 422 JSON response (API).
Longer Answer
A Form Request (php artisan make:request StoreOrderRequest) keeps controllers thin and makes validation reusable and testable. It has rules(), authorize(), messages(), prepareForValidation() for normalising input and after() hooks for cross-field checks.
Useful rules: required, sometimes, nullable, exists:table,column, unique:table,column (with ->ignore($id) on update), Rule::in, Rule::enum, array rules with items.*.qty, File and Password rule objects, and custom rule classes.
After validation, use $request->validated() or $request->safe() so only validated fields are used. Validation does not replace database constraints: a unique rule can still race, so keep the unique index.
Code Example
class StoreOrderRequest extends FormRequest
{
public function authorize(): bool
{
return $this->user()->can('create', Order::class);
}
public function rules(): array
{
return [
'items' => ['required', 'array', 'min:1'],
'items.*.product_id' => ['required', 'integer', 'exists:products,id'],
'items.*.qty' => ['required', 'integer', 'between:1,100'],
];
}
}
Key Points
validate()inline or Form Request classes.- 422 JSON for APIs, redirect with errors for web.
- Use
validated()/safe()data. - Keep database constraints; the
uniquerule can race.
More most-asked Laravel questions
- Gates or policies: how does authorization work in Laravel?
- How do queues work in Laravel?
- What is mass assignment, and how do $fillable and $guarded protect against it?
- How do database transactions work in Laravel, and what pitfalls should you know?
- Which Artisan commands would you run when deploying Laravel to production, and why?
- What is the service container, and how does dependency injection work in Laravel?
- What is the N+1 query problem in Eloquent and how do you prevent it?
- A Laravel endpoint is slow. How do you find and fix the cause?