LoginSignup
10
7

More than 5 years have passed since last update.

Laravel5.5 FormRequestで配列チェック時にメッセージへ項目番号などを表示させたい場合のやり方

Posted at

やりたいこと

LaravelのFormRequestで配列をバリデートするとき。
エラーメッセージに番号をつけたかった!

前提

Laravel 5.5
PHP 7.2.9

当初の書き方

ルール設定
public function rules()
{
    return [
        'todos.*.title' => 'required',
        'todos.*.body' => 'required'
    ];
}
public function messages()
{
    return [
        'required' => ':attributeは必須です。',
    ];
}
public function attributes()
{
    return [
        'todos.*.title' => 'タイトル',
        'todos.*.body' => '内容'
    ];
}

POSTする値
todos[0][title] : ''<ブランク>
todos[0][body] : 'TODO内容1'
todos[1][title] : 'TODOタイトル'
todos[1][body] : ''<ブランク>
表示されるメッセージ
タイトルは必須です。
内容は必須です。

どっちのエラーなのか、ぱっと見わからないね!!!

対応

ちょっと泥臭い方法ですが。

public function attributes()
{

    $attributes = [];

    foreach ($this->request->get('todos') as $key => $value){

        $todoNumber = $key + 1;

        $attributes = array_merge(
            $attributes,
            [
                "todos.$key.title" => "TODO No.$todoNumber タイトル",
                "todos.$key.body" => "TODO No.$todoNumber 内容",
            ]
        );
    }

    return $attributes;
}
表示されるメッセージ
TODO No.1 タイトルは必須です。
TODO No.2 内容は必須です。

どっちのエラーなのか、わかりやすくなりましたね!

10
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
7