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
Category:

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).

Comments

Add new comment

Restricted HTML

Search

Page Facebook

Become a patron

If you need some help or you search a Drupal freelancer don't hesitate to contact us.

 

Contact Us

All the content is FREE but I still need your help

 

Become a patreon