0
votes

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.

2
Try $user->phone()->get()->toArray()Dev
how about $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

2 Answers

2
votes

Using brackets will return a query builder instance. This is usually more helpful for direct manipulation, for instance, if a user has many phones (I know in your case it's only one phone)

$activePhone = $user->phones()->where('status', 'active')->first(); 
//returns the first phone number with an active status

toArray() is not a member of query builder, thus, it won't work with

$user->phone()->toArray();
1
votes

As your phone function is used for relationship, you have to call it as property. you may have missed the following line in the documentation.

Once the relationship is defined, we may retrieve the related record using Eloquent's dynamic properties. Dynamic properties allow you to access relationship methods as if they were properties defined on the model

When you call it as property, laravel understand this is a relationship with other table and execute it accordingly. since all relationships also serve as query builders, when you are calling $user->phone()->toArray(), returns query builder object and search toArray() function on that class.