Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will multiple calls to Eloquent dynamic property hit the database multiple times?

http://laravel.com/docs/4.2/eloquent#dynamic-properties

class Phone extends Eloquent {

    public function user()
    {
        return $this->belongsTo('User');
    }

}

$phone = Phone::find(1);

Now, if I then do something like this:

echo $phone->user->email;
echo $phone->user->name;
echo $phone->user->nickname;

Will Eloquent make a database call for every time I use the ->user dynamic property? Or is this smart enough to cache the user on the first call?

like image 671
thomthom Avatar asked Feb 11 '15 04:02

thomthom


People also ask

What is dynamic property in Laravel?

Based on this, is it correct to say that the 'dynamic property' is a one-time call to the database when the property value is first called and it loads a collection. That collection can then be operated upon with the various methods like first() but the underlying data will not change.

How does Laravel eloquent work?

Laravel Eloquent, in short, helps to do a simplified synchronization of the multiple databases which are running on many different systems. Your primary responsibility is just to define database tables and the relations which exist between them.

Why ORM is used in Laravel?

The Eloquent ORM included with Laravel provides a beautiful, simple ActiveRecord implementation for working with your database. Each database table has a corresponding "Model" which is used to interact with that table. Before getting started, be sure to configure a database connection in config/database. php .

What is query scope in Laravel?

A scope is a method in your model that makes it able to add database logic into your model. Scopes make it able to reuse query logic by allowing to encapsulate database logic into a model.


1 Answers

In your example, the user attribute on the $phone object will be lazy loaded, but it will only be loaded once.

Keep in mind, as well, that once the object is loaded, it does not reflect any changes to the underlying table unless you manually reload the relationship using the load method.

The following code illustrates the example:

$phone = Phone::find(1);

// first use of user attribute triggers lazy load
echo $phone->user->email;

// get that user outta here.
User::destroy($phone->user->id);

// echoes the name just fine, even though the record doesn't exist anymore
echo $phone->user->name;

// manually reload the relationship
$phone->load('user');

// now will show null, since the user was deleted and the relationship was reloaded
var_export($phone->user);
like image 187
patricus Avatar answered Nov 10 '22 08:11

patricus