I setup the user
- phone
relationship explained in the laravel docs here:
https://laravel.com/docs/5.4/eloquent-relationships
$user=Auth::user();
$phone = $user->phone;
var_dump($phone->toArray());
This worked fine, and displayed the phone data from the database.
What I don't understand is why I am using $user->phone
instead of $user->phone()
.
From the docs, my user model contains this function:
public function phone()
{
return $this->hasOne('App\Phone');
}
But when I try to access $user->phone()->toArray()
, it throws an error that the method is not found.
Why am I accessing phone
as a property and not a function? Is it possible to use the function instead? My IDE does not recognize a phone
attribute for $user, only the phone()
function.
$user->phone()->get()->toArray()
– Dev$phone = $user->phone()->get();
then$array = (array) $phone; dd($array);
– claudios$user->phone()
will return you an Eloquent relation, from which you can chain query builder functions.$user->phone
returns you the the relation instance, which is an Eloquent model. – fubar