Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

laravel - why function call with no parentheses?

I see this in a laravel tutorial :

Auth::user()->item;

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

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

where Item is for models\Item.php

So why the parentheses is not needed when item function is called ? Like : Auth::user()->item(); If I put the parentheses, the browsers goes crazy and crash.

Also, if I rename Item.php to Item2.php, rename class Item to Item2, and I do hasMany('Item2', 'owner_id'), it won't work. But why ? Where does 'Item' came from ?

Thanks,

Patrick

like image 949
trogne Avatar asked Oct 22 '14 16:10

trogne


People also ask

What happens when you call a function without parentheses?

Without parentheses, the function name is used as the pointer of the function. The name of a function is the pointer of the function. At this time, the result of the function is not obtained, because the function body code will not be run.

What is difference between calling function with and without parentheses Javascript?

With parenthesis the method is invoked because of the parenthesis, the result of that invocation will be stored in before_add. Without the parenthesis you store a reference (or "pointer" if you will) to the function in the variable.


2 Answers

Laravel uses the magic function __get to handle arbitrary attributes.

This calls Illuminate\Database\Eloquent\Model's getAttribute function, which checks the model's relations and returns the related item(s) if a relationship is present with that name.

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

like image 138
ceejayoz Avatar answered Sep 24 '22 18:09

ceejayoz


The method item() is setting up a relationship for the Eloquent ORM on how to prepare a query. calling ->item is telling Eloquent through its Dynamic Properties that you want Item and then Eloquent will use the method. You can only call the method directly if it is compatible with Query Builder. The example you give should work either way but there may be something I am missing.

like image 25
dasper Avatar answered Sep 20 '22 18:09

dasper