Laravel
Beginner
1 min read
Form Requests and Validation
Example
<?php
// app/Http/Requests/StorePostRequest.php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class StorePostRequest extends FormRequest
{
public function authorize(): bool
{
// Only authenticated users may create posts
return $this->user() !== null;
}
public function rules(): array
{
return [
'title' => ['required', 'string', 'max:255'],
'slug' => ['required', 'string', 'max:255', Rule::unique('posts')],
'body' => ['required', 'string', 'min:50'],
'status' => ['required', Rule::in(['draft', 'published'])],
'category_id'=> ['required', 'integer', 'exists:categories,id'],
'tags' => ['nullable', 'array'],
'tags.*' => ['string', 'max:50'],
'published_at'=> ['nullable', 'date', 'after_or_equal:today'],
];
}
public function messages(): array
{
return [
'body.min' => 'The post body must be at least 50 characters.',
];
}
public function attributes(): array
{
return [
'category_id' => 'category',
'published_at' => 'publish date',
];
}
}
Related Resources
Laravel Reference
Complete tag & property list
Laravel How-To Guides
Step-by-step practical guides
Laravel Exercises
Practice what you've learned
More in Laravel