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?

moses toh
  • 12,344
  • 71
  • 243
  • 443

2 Answers2

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.

Risan Bagja Pradana
  • 4,494
  • 1
  • 20
  • 22
  • 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 data – moses toh Mar 14 '18 at 17:25
  • 2
    I wonder if this should be `selected_data.*.name`, where `*` represents any index of `selected_data`. – Tim Lewis Mar 14 '18 at 17:35
  • @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. – Risan Bagja Pradana Mar 14 '18 at 20:28
  • @Risan Bagja Pradana I try comment Tim Lewis, it works – moses toh Mar 15 '18 at 00:36
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',
    ];
}
Dharman
  • 30,962
  • 25
  • 85
  • 135