Câu hỏi phỏng vấn Laravel
Câu hỏi

Where can you easily hook on validation in Laravel 5.x?

Câu trả lời

In Laravel 5.x, you can easily hook into the validation process in several ways:

1. Using the after Method on a Validator Instance

The after method allows you to attach callbacks that will be executed after the validation process is completed. This is useful for performing additional checks or adding custom error messages. Here is an example:

php Copy
$validator = Validator::make($data, [
    'email' => 'required|email',
]);

$validator->after(function ($validator) {
    if ($this->someAdditionalCheckFails()) {
        $validator->errors()->add('field', 'Something is wrong with this field!');
    }
});

if ($validator->fails()) {
    // Handle the failed validation
}

You can add as many after callbacks as needed to a validator instance[1][4][7].

2. Using the withValidator Method in Form Request Classes

Form request classes provide a convenient way to encapsulate validation logic. You can use the withValidator method to add an "after" validation hook. This method receives the fully constructed validator, allowing you to call any of its methods before the validation rules are evaluated. Here is an example:

php Copy
class StoreEventRequest extends FormRequest
{
    public function rules()
    {
        return [
            'name' => 'required',
            'date' => 'required|date',
        ];
    }

    public function withValidator($validator)
    {
        $validator->after(function ($validator) {
            if (strtotime($this->date) < strtotime('now')) {
                $validator->errors()->add('date', 'Date should be in the future.');
            }
        });
    }
}

In this example, the withValidator method is used to add a custom validation rule that checks if the date is in the future[4][8][10].

3. Custom Validation Rules

You can create custom validation rules using rule objects or by extending the Validator facade. For example, to create a custom rule object:

php Copy
php artisan make:rule Uppercase

// In app/Rules/Uppercase.php
namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class Uppercase implements Rule
{
    public function passes($attribute, $value)
    {
        return strtoupper($value) === $value;
    }

    public function message()
    {
        return 'The :attribute must be uppercase.';
    }
}

// Using the custom rule in a request
$request->validate([...
middle

middle

Gợi ý câu hỏi phỏng vấn

junior

What is Service Container?

junior

What is the Facade Pattern used for?

middle

List types of relationships available in Laravel Eloquent?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào