1

How to validate a laravel request object, I have this conditions

request()->validate([
                'avatar' => 'required|image',
                'display_name' => 'required|min:3|max:100',
                'role_id'      => 'required|integer',
                'username' => 'required|unique:users|min:4|max:15',
                'email'        => 'required|email|unique:users',
                'phone_number' => 'required|min:3',
                'password'     => 'required|min:6',
                'country_id' => 'required|integer'
]);

But in my request it was stored in an object form, what should I do to make the validations work ?

enter image description here

2 Answers 2

5

You validate it the same way you validate a multi-dimensional array:

request()->validate([
    'form.avatar' => 'required|image',
    'form.display_name' => 'required|min:3|max:100',
    'form.role_id'      => 'required|integer',
    'form.username' => 'required|unique:users|min:4|max:15',
    'form.email'        => 'required|email|unique:users',
    'form.phone_number' => 'required|min:3',
    'form.password'     => 'required|min:6',
    'form.country_id' => 'required|integer'
]);

If your form is an array of object, you can use wildcard

request()->validate([
    'form.*.avatar' => 'required|image',
    'form.*.display_name' => 'required|min:3|max:100',
    'form.*.role_id'      => 'required|integer',
    'form.*.username' => 'required|unique:users|min:4|max:15',
    'form.*.email'        => 'required|email|unique:users',
    'form.*.phone_number' => 'required|min:3',
    'form.*.password'     => 'required|min:6',
    'form.*.country_id' => 'required|integer'
]);
Sign up to request clarification or add additional context in comments.

3 Comments

Hey, I'm on laravel 5.5
Nested attribute validation is valid from Laravel 5.2 so you should be fine laravel.com/docs/5.5/…
But I get this sir :) message: "SQLSTATE[42S22]: Column not found: 1054 Unknown column 'form.username' in 'where clause' (SQL: select count(*) as aggregate from users` where form.username = chandler40)" `
1

For unique validation you can pass the field name on which you need to apply validation, by default it takes the key name.

You can use this for unique validation on object data:-

'form.username' => 'required|unique:users,username|min:4|max:15'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.