前提・実現したいこと
独学でphp(laravel)を勉強しています。
PHP(larevel)で管理画面システムを作っています。
1対多の構造を持つ親テーブル(accountテーブル)と子テーブル(planテーブル)の保存時のバリデーションを実装中です。
発生している問題
バリデーションが効かない [readouble.com](https://readouble.com/laravel/5.5/ja/validation.html)を参考に実装していたのですが、 単純なバリデーションは動くのですが、バリデーションに条件をつける方法がうまくいきません。 planデーブルの外部キーである'account_id'が同じレコードがあった場合に'genre'カラムに'genre'が重複しないように、ユニークバリデーションをかけたいのですが、。。
該当のソースコード
account.php
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Account extends Model { public $timestamps = true; protected $table = 'account', $connection = 'xxxxx', $dates = ['created_at', 'updated_at'], $hidden = ['created_at', 'updated_at']; public function created_user() { return $this->belongsTo(User::class, 'created_user_id', 'id'); } public function updated_user() { return $this->belongsTo(User::class, 'updated_user_id', 'id'); } public function account_plans() { return $this->hasMany(Plan::Class); } }
AccountRequest.php
php
1<?php 2 3namespace App\Http\Requests; 4 5use Illuminate\Foundation\Http\FormRequest; 6use Illuminate\Validation\Rule; 7 8 9class UpdateAccountRequest extends FormRequest 10{ 11 /** 12 * Determine if the user is authorized to make this request. 13 * 14 * @return bool 15 */ 16 public function authorize() 17 { 18 return true; 19 } 20 21 /** 22 * Get the validation rules that apply to the request. 23 * 24 * @return array 25 */ 26 public function rules() 27 { 28 return [ 29 ... 30 ... 31 ] 32 'account_key' => [ 33 'required', 34 'string', 35 'regex:/^[a-zA-Z0-9_-]+$/', 36 'max:32', 37 Rule::unique('distribute_account')->ignore($this->id), 38 ], 39 ※ここから 40 'genre' =>[ 41 Rule::unique('plan')->ignore($this->input('id'))->where(function ($query) { 42 $query->where('account_id', $this->input('account_id')); 43 }), 44 ], 45 ※ここまで 46 ]; 47 } 48 49 public function messages() 50 { 51 return [ 52 'account_key.required' => 'コードは必須項目です', 53 . 54 . 55 . 56 ]; 57 } 58 59}
account.edit.blade.php
php
1@php 2 $genre_name_loop = [ 3 'music' => '経済' , 4 'eiga' => '社会' , 5 ]; 6 $plan_name_loop = [ 7 0 => '有料' , 8 1 => '無料' , 9 ]; 10@endphp 11<li class="distribute-list-item cancel"> 12 <div class="form-group"> 13 <div class="col-sm-9 col-md-10 col-lg-10" style="display:inline-flex"> 14 {{ Form::select('genre[]', $genre_name_loop, $genre, ['class' => 'form-control input-max-150 bold']) }} 15 {{ Form::select('plan_num[]', $plan_name_loop, $plan, ['class' => 'form-control input-max-150 bold']) }} 16 <button type="button" class="remove-item">☓</button> 17 </div> 18 </div> 19</li> 20
試したこと
[readouble.com](https://readouble.com/laravel/5.5/ja/validation.html### 補足情報(FW/ツールのバージョンなど))
おたすけください。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/09/05 10:31
2019/09/06 07:02