Relationship Method VS Dynamic Property in Laravel with example

admin_img Posted By Bajarangi soft , Posted On 10-09-2020

Eloquent relationships are defined as methods on your Eloquent model classes. Since, like Eloquent models themselves, relationships also serve as powerful query builders, defining relationships as methods provides powerful method chaining and querying capabilities.today we are going to discuss how relationship method differ from dynamic property

Relationship Method VS Dynamic Property in Laravel with example

Relationship Method VS Dynamic Property in Laravel 

Eloquent allows you to access your relations via dynamic properties. Eloquent will automatically load the relationship for you, and is even smart enough to know whether to call the get (for one-to-many relationships) or first (for one-to-one relationships) method. It will then be accessible via a dynamic property by the same name as the relation.

Relationship Method

If you do not need to add additional constraints to an Eloquent relationship query, you may access the relationship as if it were a property. For example, continuing to use our User and Post example models, we may access all of a user's posts like so:

$user = App\User::find(1);

foreach ($user->posts as $post) {
    //
}


Dynamic Property

Dynamic properties are "lazy loading", meaning they will only load their relationship data when you actually access them. Because of this, developers often use eager loading to pre-load relationships they know will be accessed after loading the model. Eager loading provides a significant reduction in SQL queries that must be executed to load a model's relations.

 For example, with the following model $phone:

class Phone extends Eloquent {

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

$phone = Phone::find(1);
 

Instead of echoing the user's email like this:

echo $phone->user()->first()->email;


It may be shortened to simply:

echo $phone->user->email;
 

Note: Relationships that return many results will return an instance of the Illuminate\Database\Eloquent \Collection class.

Related Post