user391986
user391986

Reputation: 30906

Calling eloquent relation multiple times doesn't return data

I'm having this strange behavior in Laravel 5.1 where when I call the relation of an eloquent model more than once within the same code execution, then the second time it doesn't have the data.

class Items extends Eloquent {
    public $table = 'items'

    public function subItems() {
        return $this->hasMany(Item::class, 'items_id');
    }
}

class Item extends Eloquent {
    public $table = 'items_item'
    public $fillable = ['items_id'];
}


$items = Items::create();
Item::create([
    'items_id' => $items->id,
]);
Item::create([
    'items_id' => $items->id,
]);


// works
$first = $items->subItems;
// no data
$second = $items->subItems;
// works
$third = $items->subItems()->get();

Is this normal behavior? Do i have to somehow reset something before calling the relation again?

Upvotes: 1

Views: 106

Answers (1)

Green Sand
Green Sand

Reputation: 17

I don't know the purpose of your repeated same action. If your $first,$second,$third variables are in same function, don't repeat it again.

Instead use,

$first = $items->subItems; $second = $first;

Upvotes: 1

Related Questions