Blog Detail

14

Oct
Some Awesome Tips and Tricks for Laravel Validation cover image

arrow_back Some Awesome Tips and Tricks for Laravel Validation

Validation is the process of checking the incoming data. Laravel provides several different approaches to validate your application’s incoming data. It is most common to use the validate method available on all incoming HTTP requests. Laravel includes a wide variety of beneficial validation rules that you can apply to data, even providing the ability to validate if values are unique in a given database table. In this article, I will share some laravel validation tips and tricks in detail so that you can utilize them in your laravel application.

Stop on First Validation Error

By default, Laravel validation errors will be returned in a list, checking all validation rules. But if you want the process to stop after the first error, you can use a validation rule called bail:

$request->validate([
    'title' => 'bail|required|unique:posts|max:255',
    'body' => 'required',
]);

Image validation

While you are validating the uploaded images, you can specify the dimensions you require.

['photo' => 'dimensions:max_width=4096,max_height=4096']

Custom validation error messages

You can customize validation error messages per field, rule, and language - just create a specific language file resources/lang/xx/validation.php with the appropriate array structure.

'custom' => [
     'email' => [
        'required' => 'We need to know your e-mail address!',
     ],
],

Validate dates with “now” or “yesterday” words

You can validate dates by rules before/after and passing various strings as a parameter, like tomorrow, now, yesterday. Example: ‘start_date’ => ‘after:now’. It’s using strtotime() under the hood.

$rules = [
    'start_date' => 'after:tomorrow',
    'end_date' => 'after:start_date'
];

Validation Rule with Some Conditions

If your validation rules depend on some condition, you can modify the rules by appending withValidator() to your FormRequest class and specify your custom logic there. Like, if you want to append a validation rule only for some user role.

use Illuminate\Validation\Validator;
class StoreBlogCategoryRequest extends FormRequest {
    public function withValidator(Validator $validator) {
        if (auth()->user()->is_admin) {
            $validator->addRules(['some_secret_password' => 'required']);
        }
    }
}

Change Default Validation Messages

If you want to change the default validation error message for a specific field and specific validation rule, just add a messages() method into your FormRequest class.

class StoreUserRequest extends FormRequest
{
    public function rules()
    {
        return ['name' => 'required'];
    }
    
    public function messages()
    {
        return ['name.required' => 'User name should be real name'];
    }
}

Prepare for Validation

If you need to modify some field before default Laravel validation, or, in other words, “prepare” that field, guess what - there’s a method prepareForValidation() in FormRequest class:

protected function prepareForValidation()
{
    $this->merge([
        'slug' => Illuminate\Support\Str::slug($this->slug),
    ]);
}

Throw 422 status code without using validate() or Form Request

If you don’t want to use validate() or Form Request, but still you need to throw errors with the same 422 status code and error structure, you can do it manually, throw ValidationException::withMessages().

if (! $user || ! Hash::check($request->password, $user->password)) {
    throw ValidationException::withMessages([
        'email' => ['The provided credentials are incorrect.'],
    ]);
}

Rules depending on some other conditions

If your rules are dynamic and depend on some other condition, you can create that array of rules on the fly

    public function store(Request $request)
    {
        $validationArray = [
            'title' => 'required',
            'company' => 'required',
            'logo' => 'file|max:2048',
            'location' => 'required',
            'apply_link' => 'required|url',
            'content' => 'required',
            'payment_method_id' => 'required'
        ];

        if (!Auth::check()) {
            $validationArray = array_merge($validationArray, [
                'email' => 'required|email|unique:users',
                'password' => 'required|confirmed|min:5',
                'name' => 'required'
            ]);
        }
        //
    }

These are some handy tips and tricks related to laravel Validation. I believe that by grasping these tips, you will improve your code execution and usability. If you love them, then please share your views on our Facebook, Twitter, or Instagram.

Facebook : https://www.facebook.com/CodeBrisk

Twitter: https://twitter.com/CodeBrisk

Instagram: https://www.instagram.com/codebrisk/

Published at : 14-10-2021

Author : Rizwan Aslam
AUTHOR
Rizwan Aslam

I am a highly results-driven professional with 12+ years of collective experience in the grounds of web application development especially in laravel, native android application development in java, and desktop application development in the dot net framework. Now managing a team of expert developers at Codebrisk.

Launch your project

Launch project