Sander Van Keer
Sander Van Keer

Reputation: 900

Use variable outside foreach laravel

I have a problem with Laravel. So what am I trying to do? I'm trying to get the location from all my examples. This actually works, so as you can see I get the id of all the examples and find the locations of it from another table in my project. The var_dump in the foreach gives what I need. But I need this data outside the foreach, I need to send it to my view afterwards. But the second var_dump, the one outside the foreach only gives the location of the first id.

So my question: is there a way to get the full $locations outside the foreach.

$ids= DB::table('example')
            ->select('id')
            ->get();

        foreach($ids as $id)
        {
            $locations = example::find($id->id)->locations()->get();
            var_dump($locations);
        }

        var_dump($locations);

This is my view:

 @foreach($examples as $example)
   <h1>{{$example->name}}</h1>
   @foreach($locations as $location)
     {{$location}}
   @endforeach
@endforeach

I see al the locations from al the $examples in every $example if I print it like this, I hope you understand my question.

Upvotes: 0

Views: 2754

Answers (2)

patricus
patricus

Reputation: 62228

There is no need to build the $locations array. You can use the relationship in the view just fine.

In your controller:

// whatever your logic is to get the examples
$examples = example::with('locations')->get();

In your view:

@foreach($examples as $example)
    <h1>{{$example->name}}</h1>
    @foreach($example->locations as $location)
        {{$location}}
    @endforeach
@endforeach

Upvotes: 1

Kuba Birecki
Kuba Birecki

Reputation: 3016

Try this:

// Define locations array
$locations = [];

// Then do the following for each example:

// Define the array for locations of each example outside of the loop
$locations[$example->name] = [];

foreach ($ids as $id) {
    // Add each location to the $locations array
    $locations[$example->name][] = example::find($id->id)->locations()->get();
}

Or if you want to get a little bit more fancy, you can use array_map instead of foreach:

$locations[$example->name] = array_map(function ($id) {
    return example::find($id->id)->locations()->get();
}, $ids);

Then in the view, you simply take out the locations from the right key for each example:

@foreach ($examples as $example)
    <h1>{{ $example->name }}</h1>
    @foreach ($locations[$example->name] as $location)
        {{ $location }}
    @endforeach
@endforeach

You don't have to use the $example->name as the key, just make sure it's unique for each example you want to fetch locations for.

I hope this helps.

Upvotes: 3

Related Questions