I'm using belongsToMany with the model Riskarea because I have a pivot table called riskarea_fields which join the Riskfield model among Riskarea:
class Riskarea extends Model
{
use SoftDeletes;
protected $table = 'riskareas';
protected $fillable = [
'name',
'icon',
];
public function riskfields()
{
return $this->belongsToMany(
Riskfield::class,
'riskarea_fields',
'area_id',
'field_id'
);
}
}
In my edit.blade.php I have this code:
@foreach ($riskfields as $rf)
<option value="{{ $rf->id }}" @if (old('active', in_array($riskarea->riskfields, $rf->id))) selected="selected" @endif>
{{ $rf->name }}
</option>
@endforeach
What I'm trying to do is iterate over the riskfields property and select all riskfields options that are within riskarea->riskfields.
Unfortunately I got:
in_array(): Argument #2 ($haystack) must be of type array, int given
This is my edit method:
public function edit(Riskarea $riskarea)
{
return view('riskareas.edit', [
'riskarea' => $riskarea,
'riskfields' => Riskfield::all()
]);
}
any idea?
CodePudding user response:
Since you want to check if each id is present in the associated riskfields, pluck their IDs before hand.
public function edit(Riskarea $riskarea)
{
return view('riskareas.edit', [
'riskarea' => $riskarea,
'selectedRiskfieldIds' => $riskarea->riskfields()->pluck('id')->toArray(),
'riskfields' => Riskfield::all(),
]);
}
Then you can do
@foreach ($riskfields as $rf)
<option value="{{ $rf->id }}" @if (old('active', in_array($rf->id, $selectedRiskfieldIds))) selected="selected" @endif>
{{ $rf->name }}
</option>
@endforeach
CodePudding user response:
You have a small mistake. You are using the in_array() function incorrectly. The syntax is: in_array(mixed $needle, array $haystack) . You've got it backwards. To use the in_array function you also need an array. Therefore, you convert the collection into an array. You do this with the Laravel function toArray().
https://laravel.com/docs/8.x/collections#method-toarray.
Change it in your blade file from:
in_array($riskarea->riskfields, $rf->id)
to
in_array($rf->id, $riskarea->riskfields->toArray())).
in_array(mixed $needle, array $haystack, bool $strict = false): bool
https://www.php.net/manual/de/function.in-array.php
