Laravel Столбцы поля таблицы рюкзака (json -массив) правила проверки не работают - PullRequest
0 голосов
/ 11 июля 2020

Я использую BackpackFor Laravel, и в моем коде есть поле типа table:

$this->crud->addField([
    'label'           => 'Contact persons',
    'name'            => 'contact',
    'type'            => 'table',
    'entity_singular' => 'contact',
    'columns'         => [
        'person' => 'Person',
        'email'  => 'Email',
        'number' => 'Phone number',
        'desc'   => 'Description',
    ],
    'attributes'        => [
        'required' => true
    ],
    'max'               => 5,
    'min'               => 1,
    'wrapper'           => [
        'class' => 'form-group col-12'
    ],
    'tab' => 'Contact data',
]);

CRUD работает нормально, но когда я добавляю проверку, что-то работает неправильно.

Мой ClientRequest.php класс имеет:

public function rules()
    {
        return [
            'cif'                            => "required|spanish_tax_number|unique:clients,cif,{$this->cif},cif",
            'name'                           => 'required|min:3|max:255',
            'address'                        => 'required|json',
            'weekly_rest'                    => 'nullable|array',
            'description'                    => 'nullable|max:255',
            'leaving_date'                   => 'nullable|date',
            'leaving_date'                   => 'nullable|date',
            'image'                          => 'nullable|image|mimes:jpeg,png',
            'contact'                        => 'required|array',
            'contact.*.person'               => 'required|email'
        ];
    }

contact проверка полей работает хорошо, но когда я попытался использовать contact.*.person для проверки всех array полей с именем person , ничего не происходит.

Я использовал функцию prepareForValidation для изменения поля json формата на array формат:

protected function prepareForValidation()
    {
        $this->merge([
            'contact' => json_decode($this->input('contact'))
        ]);
    }

Если я сбрасываю входные данные, я могу просмотреть эту функцию prepareForValidation работает хорошо, но проверка ничего не делает.

Я читал здесь о проверке массива:

Я делаю это, и работает (выполните проверку в функции контроллера store / update):

Но я бы хотел сделать это без этой многословности, кодируя все в классе ClientRequest.

Я думаю, что у меня все хорошо, но не работает.

Что я делаю не так в ClientRequest?

РЕДАКТИРОВАТЬ

Вывод request()->all() внутри rules(), функция ClientRequest.php

array:15 [▼
  "_token" => "DGnGIZwertI6kupXwYgHr8as5MVbD2sPRlmbGJrK"
  "_method" => "PUT"
  "http_referrer" => "http://127.0.0.1:8000/admin/client?active=1"
  "id" => "21"
  "cif" => "123456789F"
  "name" => "Paco Porras SL"
  "address" => "Useful address, 1"
  "weekly_rest" => array:3 [▼
    0 => "2"
    1 => "3"
    2 => "4"
  ]
  "description" => "qweqwe"
  "discharge_date" => "2020-07-08"
  "leaving_date" => null
  "image" => null
  "contact" => "[{"person":"123123123","email":"sss.ssstyytrytr","number":"qwewqe","desc":"qweq"},{"person":"123123123","email":"123123","number":"123123","desc":"123213"}]"
  "current_tab" => "datos-de-empresa"
  "save_action" => "save_and_edit"
]

Вывод после prepareForValidation:

array:15 [▼
  "_token" => "DGnGIZwertI6kupXwYgHr8as5MVbD2sPRlmbGJrK"
  "_method" => "PUT"
  "http_referrer" => "http://127.0.0.1:8000/admin/client?active=1"
  "id" => "21"
  "cif" => "123456789F"
  "name" => "Paco Porras SL"
  "address" => "Useful address, 1"
  "weekly_rest" => array:3 [▼
    0 => "2"
    1 => "3"
    2 => "4"
  ]
  "description" => "qweqwe"
  "discharge_date" => "2020-07-08"
  "leaving_date" => null
  "image" => null
  "contact" => array:2 [▼
    0 => {#1557 ▼
      +"person": "123123123"
      +"email": "sss.ssstyytrytr"
      +"number": "qwewqe"
      +"desc": "qweq"
    }
    1 => {#1556 ▼
      +"person": "123123123"
      +"email": "123123"
      +"number": "123123"
      +"desc": "123213"
    }
  ]
  "current_tab" => "datos-de-empresa"
  "save_action" => "save_and_edit"
]

РЕДАКТИРОВАТЬ 2

Я делаю это в функции сохранения / обновления ClientController.php:

$validate = Validator::make($request->all(), [
            'contact'                          => 'required|array',
            'contact.person'                   => 'required|string',
            "contact.*.person"                 => 'required|string',
        ]);

dd($validate->messages());

И результат:

Illuminate\Support\MessageBag {#1520 ▼
  #messages: array:2 [▼
    "contact" => array:1 [▼
      0 => "El campo contact debe ser un array."
    ]
    "contact.person" => array:1 [▼
      0 => "El campo contact.person es obligatorio."
    ]
  ]
  #format: ":message"
}

Что-то не работает, потому что 'contact.*.person' отсутствует.

1 Ответ

0 голосов
/ 11 июля 2020

изменить

'contact' => json_decode($this->input('contact'))

на

'contact' => json_decode($this->input('contact'), true)

и оставить свои старые правила

...