Using an accessor mutator with a to belongs relation

Using Laravel 4 and I have a mutator configured in my User model:

public function getFullnameAttribute($value)
{
    return $this->first_name. ' ' .$this->last_name;
}

      

But I have a relationship set up in my Cars model for the user id associated with this car:

public function salesManager()
{
    return $this->belongsTo('User', 'sales_manager')->select('first_name', 'last_name');
}

      

I call this the relationship on my Car table:

$cars = Car::with('marqueBasic', 'modelBasic', 'salesManager')
    ->get();

      

Now how can I do eg.

$car->salesManager->fullname

      

Currently not working, which I am assuming, because its in the other model the one that is being called?

Error: "Trying to get a property of a non-object"

Am I calling the mutator in the wrong place? I tried to put it in relationship select fields but also searched for full name and error field name.

+3


source to share


1 answer


The likely reason is that you are defining a list of fields to be retrieved for the relationship.

To understand why you need to first understand how Eloquent eagerly loads the salesManager relation when you ask it to retrieve all the cars using SalesManager . In such a situation, "Eloquent" does the following:

  • Load all cars
  • Get values ​​of sales_manager columns for all loaded cars
  • Load all users who have an ID within the values ​​from point 2.
  • The map loads custom models into vehicles by matching the selected user's model id and the sales_manager column.


As you can see, step 4 cannot be done. The user id field is not listed in the list of fields that will be selected for the salesManager relationship , so Eloquent will not have a way to map the selected users to cars when the salesManager is actively loaded . You need to add the field you are referring to to your salesManager list relation:

public function salesManager()
{
    return $this->belongsTo('User', 'sales_manager')->select('first_name', 'last_name', 'id');
}

      

+1


source







All Articles