I am trying to save the input of some checkboxes.
I have a table users_cities as:
id_user | id_city
--------+---------
1 | 1
1 | 2
2 | 1
And I have a view which brings three checkboxes.
city1 city2 city3, on that case for id_user = 1
would bring city1 and city2 checked.
what I am trying to do is, if the user selects box 3 and uncheck box 2 or just select box 3, the Eloquent would recognise and sync the data with the database.
public function update($id)
{
$city[] = \App\City::find($id);
$input = Request::all();
//Tried: $city->sync($input)
//Also tried: $city->delete(); $city->save($input);
return redirect()->back();
}
I have the id_user
on the $city
variable and the cities on $input
but I can't get this to work.
VIEW:
@extends('welcome')
@section('content')
<h1>Atualizar cidades</h1>
@foreach ($city as $citySelect)
<?php $number[] = $citySelect->id_city; ?>
@endforeach
{!! Form::model($city, ['route' => ['cities.update', $citySelect->id_user]]) !!}
@foreach ($cidades as $cidadesnome)
{!! Form::checkbox($cidadesnome->id, $cidadesnome->name, (in_array($cidadesnome->id, $number)), ['class' => 'field']) !!}{!! $cidadesnome->name !!}
@endforeach
<button class="btn btn-success" type="submit">
Atualizar Cidades
</button>
{!! Form::close() !!}
@stop
Relations:
public function cities() {
return $this->belongsToMany('City', 'users_cities', 'id_city', 'id_user');
}
public function users() {
return $this->belongsToMany('Users', 'users_cities', 'id_user', 'id_city');
}
I have the
id_user
on the$city
variable and the cities on$input
but I can't get this to work.
That is not posible since you used $city[] = \App\City::find($id);
and therefore $city
is not id_user
but an array that contains one instance of App\City
.
What you need to do in order to sync the cities of an user whose id is in $id
is:
public function update($id)
{
$user = \App\User::findOrFail($id);
$input = Request::all();
$user->cities()->sync($input['cities']);
return redirect()->back();
}
You also need to change your checkboxes name to send an array of cities and have the name cities[]
@foreach ($cidades as $cidadesnome)
<label>
{!! Form::checkbox('cities[]', $cidadesnome->id, (in_array($cidadesnome->id, $number)), ['class' => 'field']) !!}{!! $cidadesnome->name !!}
</label>
@endforeach
All that assuming you defined the proper relationships in your models. I see you are not following Eloquent naming convention for your column names. I highly recommend you follow them. They will make your relationships definitions much easier.