Move Laravel Article Validation into a Form Request
Keep controllers focused by moving validation and access checks into a dedicated Form Request.
You are reading a translated version.
An article controller becomes harder to read when validation is mixed with persistence and other work. A Form Request defines accepted input and who may submit it.
This example assumes a Laravel application with a Post model, title and body columns, and users with an is_admin attribute. Generate the request with php artisan make:request StoreArticleRequest, then replace its methods as shown.
Implementation example
public function authorize(): bool
{
return $this->user()?->is_admin === true;
}
public function rules(): array
{
return [
'title' => ['required', 'string', 'max:200'],
'body' => ['required', 'string', 'max:50000'],
];
}
// In ArticleController:
public function store(\App\Http\Requests\StoreArticleRequest $request)
{
$data = $request->validated();
$post = new \App\Models\Post;
$post->title = $data['title'];
$post->body = $data['body'];
$post->user_id = $request->user()->id;
// Fill any other required columns in your application's schema.
$post->save();
return response()->json(['id' => $post->id], 201);
}
Check access and input
Connect the controller to an authenticated route. Cast is_admin to boolean on the User model. Submit an empty title as an admin and verify validation fails; submit valid data as a regular user and verify access is denied.
Use validated() to keep unrelated fields out of persistence. If your schema requires a slug, category, or excerpt, add the corresponding rules and assignments before running the example. Use a policy when your application needs more detailed permissions.
