Ruleクラスからドットを含むキー名のattributeを取得する

まずカスタムルールクラスでは任意のバリデーションエラーメッセージを返せます。

class ImageRule implements Rule
{
    public function passes($attribute, $value)
    {
        // do something
    }

    public function message()
    {
        return 'The :attribute must be image';
    }
}

この時、resources/lang/{locale}/validation.phpの共通エラーメッセージを引用して共通化する場合、少々手間がかかります。 方針としてはメッセージ生成にattribute名が必要なため、passesメソッド内でメッセージを生成し、messageメソッドではそれを返すようにします。

class ImageRule implements Rule
{
    private $message;

    public function passes($attribute, $value)
    {
        // do something

        $this->message = 'message';
    }

    public function message()
    {
        return $this->message;
    }
}
// image: 'message.'

次に翻訳されたメッセージを取得します。今回は既存のimageルールのメッセージ形式を利用します。

class ImageRule implements Rule
{
    private $message;

    public function passes($attribute, $value)
    {
        // do something

        $this->message =  __('validation.image');
    }

    public function message()
    {
        return $this->message;
    }
}
// image: 'The :attribute must be an image.'

最後にattribute名も同様に取得します。 この時、キー名がネストしていない(ドットを含まない)場合はそのままキー名で取得できます。

// validation.php
'attributes' => [
    'user.image' => 'Image',
],

class ImageRule implements Rule
{
    private $message;

    public function passes($attribute, $value)
    {
        // do something

        $this->message =  __('validation.image', ['attribute' => __('validation.attributes.'.$attribute)]);
    }

    public function message()
    {
        return $this->message;
    }
}
// image: 'The Image must be an image.'

キー名がネストしている場合(user.imageなど)一旦翻訳データ一覧を取得する必要があります。 $attribues['user.image'] ではなく、$attribues['user']['image'] へアクセスしてしまうドット記法の弊害です。

// validation.php
'attributes' => [
    'user.image' => 'Avatar Image',
],

class ImageRule implements Rule
{
    private $message;

    public function passes($attribute, $value)
    {
        // do something

        // validation.attributes配列のuser.imageキーの値を取得。
        $tranlated_attribute = app('translator')->get('validation.attributes')[$attribute];
        $this->message = __('validation.image', ['attribute' => $tranlated_attribute]);
    }

    public function message()
    {
        return $this->message;
    }
}
// user.image: 'The Avatar Image must be an image.'

'validation.attributes."user.image", 'validation.attributes.[user.image] などでもダメでした。