James
James

Reputation: 310

Foreach loop seems to destroy the array in Laravel / PHP 7

I have a simple CRUD item called Filters. In here each filter is assigned to a category with a foreign key. What I am trying to do is loop through each foregin key to get the category name rather than id to display to the user.

I get all filters first and performed a die/dump to check all results were there and they are.

When trying to assign the category name to the correct array item I get this error:

"Indirect modification of overloaded element of App\Filter has no effect"

So to check what's happening I have die/dumped inside the foreach loop and the exact same data has now disappeared. Even if I just put a foreach loop in with no modiifcaiton of the original array, when I pass this back to the view it has been unset.

AM I being very naive and not realising something this foreach loop does that destroys this data???

I have copied my code below and commented where the dd works and doesn't;

public function show()
{   
    $filter = [];
    $filter['filters'] = Filter::all();

    //dd($filter['filters']); --this works fine here
    foreach($filter['filters'] AS $key => $filter){
    //dd($filter['filters']); --this returns null here
        $category = Category::where('id', $filter->category)->first();
        $filter['filters'][$key]->category = $category->category;
    }

    return view('admin.crud.filters.index')->with('filter', $filter);
}

Upvotes: 0

Views: 582

Answers (1)

Afraz Ahmad
Afraz Ahmad

Reputation: 5386

Don't re-initialize a variable or different data-type with same name

Try to change the $filter to something else in foreach loop. Because you already have an array with same name.

Do something like:

foreach($filter['filters'] AS $key => $f){...}

Upvotes: 1

Related Questions