Why a function call without parentheses?

I see this in the laravel lesson:

Auth::user()->item; 

where item is a function, inside \ User.php models:

 function item() { return $this->hasMany('Item', 'owner_id'); } 

where Item for models \ Item.php

So why brackets are not needed when calling an element function? For example: Auth::user()->item(); If I put brackets, browsers go crazy and crash.

Also, if I rename Item.php to Item2.php, rename the Item class to Item2 and I do hasMany('Item2', 'owner_id') , this will not work. But why? Where did the element come from?

Thanks,

Patrick

+5
source share
2 answers

Laravel uses the __get magic function to handle arbitrary attributes.

This calls the Illuminate\Database\Eloquent\Model getAttribute , which checks the model relationships and returns related elements (elements) if the relationship is present with this name.

Brackets are not needed because getAttribute automatically executes the items() function when the items attribute is requested. You can, by the way, request Auth::user()->item(); which will return a query builder that you can work with.

+6
source

The item() method establishes a link for the Eloquent ORM on how to prepare the request. a call to ->item tells Eloquent through "Dynamic Properties" in which you want to "Item" and then "Eloquent" will use this method. You can call a method directly only if it is compatible with Query Builder . The example you give should work anyway, but maybe something is missing from me.

+1
source

Source: https://habr.com/ru/post/1205292/


All Articles