I have an array just like this:
The question I have is how can I foreach through the objects. I want to associate each of those to a container.
So I tried this:
foreach ($data['plates'] as $index => $element) {
//Don't worry about the container_id.
$plates = Plate::find($element['plate_id'])->plateContainer()->associate($data['container_id'])->save();
}
But can't seem to get this working. Any ideas what I am doing wrong or missing?
FYI—The relations between the models
Plate Model
public function plateContainer()
{
return $this->belongsTo('App\Models\PlateContainer');
}
PlateContainer Model
public function plates()
{
return $this->hasMany('App\Models\Plate');
}
Update #1: The array is coming from AngularJS after submitting a simple form. Sorry forgot to mention this.
Update #2: Ok. I gave the following a try.
foreach ($data['plates'] as $element)
{
foreach ($element as $value)
{
$plates = Plate::find($value)->plateContainer()->associate($data['container_id'])->save();
}
}
…but still not getting it to work. Checking the DB, it only shows the first plate was updated with the given container.
I tried dd($value);
It only shows 1