15
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Laravel】バリデーションやフォームリクエストのattributesとは?カスタム属性名の設定方法

Last updated at Posted at 2021-01-21

バリデーション関連のファイルでattributesというのが出てくる。この役割と使い方について。

目次

  1. いつ使うか?
  2. 属性名の変更方法
  3. フォームリクエストを使用している場合

## いつ使うか? バリデーションでデフォルトのエラーメッセージを表示すると、その属性名が表示される。この属性名は変数で適用されている。

attributesを編集することで、この属性名を好きな値に変更することができる。


### デフォルトの設定例 `name`属性に以下バリデーションが適用されている場合
バリデーションルール
'name' => 'required|min:3|max:10',
image.png

resources > lang > en > validation.php で定義された内容が表示されている。

image.png

validation.php
    'min' => [
        'string' => 'The :attribute must be at least :min characters.',
    ],

ここで、属性名は:attributeというように可変な値で定義されている。


### 属性名の変更方法 上記validation.phpの一番下にある`attributes`に追記する。
validation.php
    'attributes' => [
        'name' => '名前',
    ],

**▼実行例**
image.png

:attributeの部分が指定した「名前」に変更されている。


## メッセージを変更する方法 メッセージを変更したい場合は、同ファイルの下の方にある`custom`に追記する。
validation.php
    'custom' => [
        //以下追記
        'name' => [
            'min' => ':attributeは:min 文字以上で入力してください'
        ],
    ],

**▼実行例**
image.png

## 日本語化 現在、enディレクトリ配下のファイルをいじっているが、日本語なので、本来はjaディレクトリのファイルをいじるべき。

日本語化の方法はこちらを参照。


## フォームリクエストを使用している場合 フォームリクエストを使用している場合、**各ファイルのクラスの定義内で`attribute`を設定することができる**。

フォームリクエストとは?

フォームリクエストにカスタム属性を追加

attributesメソッドを新たに作成する。

作成例
    public function attributes()
    {
        return [
            'name' => '名前',
        ];
    }

**▼フォームリクエストの設定例**
MailFormRequest.php
<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class MailFormRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'name' => 'required|min:3|max:10',
        ];
    }


    public function messages()
    {
        return [
            'name.required' => '名前を入力して下さい。',
            'name.max' => ':attributeは:max文字以下で入力して下さい。',
            'name.min' => ':attributeは:min文字以上で入力して下さい。',
        ];
    }

    public function attributes()
    {
        return [
            'name' => '名前',
        ];
    }
}

▼バリデーション実行結果

image.png
15
9
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
15
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?