Anastasie Laurent
Anastasie Laurent

Reputation: 1179

laravel loop over collection

I have this code:

$data = new Restaurant(array('id' => $restaurant_id));
        $data = $data->waitingtimes();
        foreach($data as $oneTime){
            echo $oneTime->value;
        }
exit;

as you see, I tried to print the value attribute for each $data, but I got empty results.

However, when I do this:

$data = new Restaurant(array('id' => $restaurant_id));
        $data = $data->waitingtimes();
        echo $data->first()->value; exit;

I get results, so the $data absolutely has values in it.

I tried to read the basecollection class documentation here https://github.com/laravel/framework/blob/master/src/Illuminate/Database/Eloquent/Collection.php

but there is nothing about loop.

I also read the conllection class documentation here http://laravel.com/api/source-class-Illuminate.Database.Eloquent.Collection.html#5-73 but there is nothing about loop.

Upvotes: 1

Views: 1634

Answers (3)

Anmol Kumar
Anmol Kumar

Reputation: 121

replace $data = $data->waitingtimes(); by

$data = $data->waitingtimes()->get();

Upvotes: 1

The Alpha
The Alpha

Reputation: 146191

You may also try this:

$data = Restaurant::find($restaurant_id);

This will give you only one Restaurant by it's id and if waitingtimes is a relationship/related model then you may try this (known as eager loading, better than dynamic call):

$data = Restaurant::with('waitingtimes')->find($restaurant_id);

Then you may loop like:

foreach($data->waitingtimes as $waitingtime) {
    echo $waitingtime->value;
}

Upvotes: 2

Razor
Razor

Reputation: 9835

replace $data = $data->waitingtimes(); by

$data = $data->waitingtimes()->get();

Upvotes: 4

Related Questions