更新多个checbox Laravel

时间:2017-11-07 09:13:18

标签: php laravel checkbox

我有一个表格关联

ID_USER_CAR | USER_ID | CAR_ID | DELETED_AT

1               2         3        
2               2         5
3               2         10

问题在于更新......因为下次我正在编辑时......用户2只想要列车3和另一辆车...例如汽车7。

 @foreach($cars as $car)
     <label style="display:block" class="custom-control custom-checkbox">
      <input @if(in_array($car->car_id, $userCars)) checked @endif type="checkbox" name="cars[]" value="{{ $car->id_car }}" class="custom-control-input"><span class="custom-control-indicator"></span><span class="custom-control-description">{{ $car->name }}</span>
     </label>
  @endforeach

所以更新后......表格看起来像这样

 ID_USER_CAR | USER_ID | CAR_ID | DELETED_AT

    1               2         3        
    2               2         5    2017-10-15
    3               2         10   2017-10-15
    4               2         7

1 个答案:

答案 0 :(得分:0)

你可以在laravel中使用Eloquent Relationships来解决这个问题:

假设您的表格名称为car_user

创建2个模型:汽车和用户:
在Car model中添加users()关系:

    public function users(){
        return $this->belongsToMany( User::class, 'car_user', 'car_id', 'user_id' );
    }  
用户模型中的

    public function cars(){
        return $this->belongsToMany( Car::class, 'car_user', 'user_id', 'car_id' );
    }  

现在你可以在刀片中执行此操作:

@foreach($cars as $car)
     <label style="display:block" class="custom-control custom-checkbox">
      <input {{ $car->users->find($user->user_id) ? 'checked' : '' }} type="checkbox" name="cars[]" value="{{ $car->id_car }}" class="custom-control-input"><span class="custom-control-indicator"></span><span class="custom-control-description">{{ $car->name }}</span>
     </label>
  @endforeach

现在更新:
在多对多关系更新中,您必须首先分离所有行,然后附加新行(已检查的行):
controller

public function update(Request $request)
{
    $user->cars()->detach();
    foreach ($request->cars as $car)
        $user->cars()->attach($car);
}