0

I have an array just like this:

enter image description here

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

4
  • Is it a js array or a php array? Commented Sep 29, 2016 at 14:44
  • Why is javascript tagged here? Commented Sep 29, 2016 at 14:44
  • @callback I am sorry. I forgot to mention. The array coming from AngularJS . I will update the post Commented Sep 29, 2016 at 14:45
  • @Pete Sorry! Just updated the post. No it's not a php array. Coming from AngularJS Commented Sep 29, 2016 at 14:47

2 Answers 2

1

Your $data['plates'] contains 2 associative arrays: [0] => {etc...} and [1] => {etc...}. So you need a nested loop for that.

for ($i=0; $i<count($data['plates']); $i++) {
    foreach ($data['plates'][$i] as $index => $element) {
    //Don't worry about the container_id. 
    $plates = Plate::find($element['plate_id'])->plateContainer()->associate($data['container_id'])->save();
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, but what if I had more than 2 elements?
Updated my answer. Instead of hard coding the loop limit, use count() function instead to count the number of elements of the array.
I tried this again. It's weird, it only updates a single plate with a given container. I updated my post once again.
Why find($value)? Why not find($value['plate_id'])?
0

Something was off.

   foreach ($data['plates'] as $index => $element) {


  $plates = Plate::find($element['plate_id'])->plateContainer()->associate($data['container_id'])->save();
}

Did the trick

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.