Introduction:
Start with why request validation is important in Laravel:
- Ensures clean, validated data for robust applications.
- Makes controllers cleaner and more manageable.
- Offers flexibility for custom rules and messages.
Mention briefly what the readers will learn:
- How to create and configure a request class in Laravel.
- Setting up validation rules and custom error messages.
- Integrating the request class into a controller.
1. Creating a Request File
Begin by explaining what a request class is:
- A request class centralizes input validation logic.
Command to Create the Request File:
php artisan make:request DesignationRequest
Explain what happens:
- Laravel generates a
DesignationRequest
class in theApp\Http\Requests
directory.
2. Understanding the Generated Request Class
a) The authorize()
Method
- By default,
authorize()
returnsfalse
. - Change it to
true
to allow all users or implement authorization logic if needed.
public function authorize()
{
return true;
}
b) The rules()
Method
- Define validation rules for the input fields.
Example:
public function rules()
{
return [
'name' => 'required|string|min:3|max:255',
'description' => 'nullable|string|max:555',
];
}
c) The messages()
Method
- Customize error messages for specific fields.
Example:
public function messages()
{
return [
'name.required' => 'The designation name is required',
'name.min' => 'The designation name must be atleast 3 characters',
'name.max' => 'The designation name must not exceed 255 characters',
'description.max' => 'The description must not exceed 555 characters'
];
}
3. Integrating the Request Class in the Controller
Explain how to configure the request file with a controller.
- Add the
use
statement:
use App\Http\Requests\DesignationRequest;
- Update the
store
method to use the request class:
public function store(DesignationRequest $request)
{
$designation = Designations::create([
'name' => $request->validated('name'),
'description' => $request->validated('description'),
'active_status' => $request->has('active_status') ? 1 : 0,
]);
return redirect()->route('admin.designations.index')
->with('success', 'Designation created successfully!');
}
Top comments (0)