n Relationship Methods Vs. Dynamic Properties in Laravel | CodimTh

Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh

Relationship Methods Vs. Dynamic Properties 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.

That said, using the method defined for the database relationship or the dynamic property (accessor) will behave differently.

If you issue the post count using the method as follows:

$count = $tag->posts()->count();

That will generate the proper SQL with the COUNT aggregate function.

In the other hand, if you issue the post count using the dynamic property (accessor) as follows:

$count = count($tag->posts);

That will fetch all the posts, convert them to an array of objects, then counting the number of element of the array.

In your case, the choice should depend of the usage of the posts related to a tag. If you just want to count, then use the method and the aggregate function. But, if apart from counting you will be doing something else with those posts, then use the dynamic property (accessor).

Riadh Rahmi

Senior Web Developer PHP/Drupal & Laravel

I am a senior web developer, I have experience in planning and developing large scale dynamic web solutions especially in Drupal & Laravel.

Web Posts


Page Facebook