Laravel 8 Validation for: Form Request, API, Dynamic URL

Laravel 8 Validation

In Laravel 8, you can use form request classes to handle validation for yo application. Form request classes allow you to centralize your validation logic and keep it separate from your controller methods.

To create a form request class, you can use the make:request Artisan command:

php artisan make:request MyFormRequest

This will create a new form request class in the app/Http/Requests directory. You can then define your validation rules in the rules method of the form request class:

public function rules()
{
    return [
        'name' => 'required|string|max:255',
        'email' => 'required|email',
        'password' => 'required|string|min:8|confirmed',
    ];
}

To use the form request class, you can type-hint it in your controller method:

public function store(MyFormRequest $request)
{
    // The request has already been validated by the form request class.
    // You can now create a new resource using the validated data.
}

If the request fails validation, the form request class will automatically redirect the user back to the previous page with the errors and input data.

You can also customize the error messages and the redirect URL by defining the messages and redirect methods in your form request class.

To use the form rquest class with an API, you can return a JSON response with the errors if the request fails validation:

if ($request->fails()) {
    return response()->json(['errors' => $request->errors()], 422);
}

You can also use the form request class with dynamic URLs by using route model binding. In your form request class, you can define a route method that specifies the model and the key used for the binding:

public function route($request)
{
    return [
        'user' => User::where('id', $request->route('id'))->firstOrFail(),
    ];
}

Then, in your controller method, you can type-hint the model and use it in your logic:

public function update(MyFormRequest $request, User $user)
{
    // The user model has been automatically resolved by the form request class.
    // You can now update the resource using the validated data.
}

This will bind the $user variable to the model instance with the matching key in the URL. If the model is not found, the form request class will automatically return a 404 response.