How can I validation object string with validation laravel?
Asked Answered
G

2

7

I use laravel 5.6

I use https://laravel.com/docs/5.6/validation#form-request-validation to validation server side

My controller like this :

<?php
....
use App\Http\Requests\UserUpdateRequest;

class UserController extends Controller
{
    ...
    public function update(UserUpdateRequest $request)
    {
        // dd($request->all());
    }
}

Before run statement in the update method, it will call UserUpdateRequest to validation server side

The validation like this :

namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class UserUpdateRequest extends FormRequest
{
    ....
    public function rules()
    {
        dd($this->request->all());
        return [
            'name'          => 'required|max:50',
            'gender'        => 'required',
            'birth_date'    => 'required',
            'address'       => 'required',
            'status'        => 'required'
        ];
    }
}

The result of dd($this->request->all()); like this :

Array
(
    [selected_data] => {"name":"agis","gender":"2","birth_date":"2018-03-13","address":"london"}
)

How can I validation if the data is object array like that?

Garrett answered 14/3, 2018 at 14:23 Comment(0)
S
14

You can use a dot notation like so:

public function rules()
{
    return [
        'selected_data.name' => 'required|max:50',
        'selected_data.gender' => 'required',
        'selected_data.birth_date' => 'required',
        'selected_data.address' => 'required',
        'selected_data.status' => 'required',
    ];
}

Read more about it here: Validating Array.

Hope this helps.

Starve answered 14/3, 2018 at 14:33 Comment(4)
There exist error like this : The given data was invalid. The selected data.name field is required. The selected data.gender field is required. etc. Whereas I had fill the dataGarrett
I wonder if this should be selected_data.*.name, where * represents any index of selected_data.Sports
@SuccessMan Try to dump the selected_data input only. If you try to dump it within the UserUpdateRequest class, you can do it like so: dd($this->request->get('selected_data')). Check if it's an array or string. From your explanation above, the selected_data looks like a JSON string.Starve
@Risan Bagja Pradana I try comment Tim Lewis, it worksGarrett
P
3

I would add the * because if you pass multiple objects you need to verify them all.

So like this:

public function rules()
{
    return [
        'selected_data.*.name' => 'required|max:50',
        'selected_data.*.gender' => 'required',
        'selected_data.*.birth_date' => 'required',
        'selected_data.*.address' => 'required',
        'selected_data.*.status' => 'required',
    ];
}
Pontiff answered 29/7, 2020 at 7:0 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.