I want to check either the countries exist in countries and the checkbox will be displayed. The values is directly from the database. I can't set the value at the input since it is array/multiple values. So, I want to check every array so that it will be a checkbox.
Controller :
public function edit($id)
{
$region = Region::find($id);
$countries = Country::all();
$country_region = DB::table('regions')
->select('countries.id', 'countries.name')
->join('country_region', 'regions.id', '=', 'country_region.region_id')
->join('countries', 'country_region.country_id', '=', 'countries.id')
->where('regions.id', '=', $id)
->get();
$items = array(
'region' => $region,
'countries' => $countries,
'country_region' => $country_region,
);
return view('admin.region.edit')->with($items);
}
blade
<div class="form-group">
<label>Choose Country</label>
<select id="test" type="checkbox" name="country_id[]">
@foreach ($countries as $item)
<option value="{{$item->id}}" selected @if (in_array($item->id, array_keys($country_region))) checked="checked"
@endif>{{$item->name}}
</option>
@endforeach
</select>
</div>
As you can see, I put php statement inside the blade to check either $country_region is exist in the countries or not. I got errors that related to the array such below :
array_keys() expects parameter 1 to be array, object given
Database :
Region Table :
$item->id
is an object but you put that onin_array()
method