1
0

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 1 year has passed since last update.

【Laravel】array型で送信されたリクエストにバリデーションを適用する

Posted at

概要

複数の要素を送信するフォームがある場合にname属性 url[] についてのバリデーション方法をまとめる

index.blade.php
@if($user->id)
    <input type="hidden" name="user_id" value="{{$user->id}}">
@endif

<label class="col-md-2 col-form-label text-md-right">
    URL
</label>
<div class="col-md-12 mb-4 domain_area">
    <input type="url" name="url[]" class="form-control"
           value="" placeholder="https://example.com/">
</div>
<div class="col-md-2">
    <input type="button" value="+" class="add btn btn-secondary">
    <input type="button" value="-" class="del btn btn-secondary">
</div>

リクエストクラスを定義

name属性名.*とすることでarray型の要素に対してバリデーションを適用できます

return [
    'url' => ['required', 'array'],
    'url.*' => ['required', 'url', 'max:255', 'distinct', $uniqueUrlValidate],
];
<?php

namespace App\Http\Requests;

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

    /**
     * バリデーションエラーのカスタム属性の取得
     *
     * @return array
     */
    public function attributes()
    {
        return [
            'domain' => 'ドメイン',
            'domain.*' => 'ドメイン',
        ];
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules(Request $request)
    {
        // 更新時は挿入先に自分自身を除いて重複チェックする
        $userId = $request->input('user_id');
        $uniqueUrlValidate = Rule::unique('users', 'url');
        !is_null($userId) ? $uniqueUrlValidate->whereNot('id', $userId) : $uniqueUrlValidate;

        return [
            'url' => ['required', 'array'],
            'url.*' => ['required', 'url', 'max:255', 'distinct', $uniqueUrlValidate],
        ];
    }
}
1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?