Home > OS >  Repleace relationship by name of this relationship
Repleace relationship by name of this relationship

Time:09-03

I have a model User with fileds like - colorhair_id, nationality_id, etc. Of course I have a relationship to other model. Problem is that I want to return nationality from User i must do that:

User::find(1)->colorhair->name

In next time I need to use

User::find(1)->nationality->name

It works but it's not look professional and it's dirty. How can I change query or something else to return object with repleace field like nationality_id to nationality with name of that. Any idea?

CodePudding user response:

You can use Laravel Mutators. Put below two functions into the User model

public function getHairColorNameAttribute(){
        return $this->colorhair->name
}

public function getNationalityNameAttribute(){
    return $this->nationality->name
}

Then when you simply access it.

User::find(1)->hair_color_name;

The next time

User::find(1)->nationality_name;

If you want to get these values by default use $append in the model. Put the following line to the top of the User model

protected $appends = ['hair_color_name','nationality_name'];

Note: In laravel 9 mutators little bit different from the above method.

Bonus Point : if you access values in the same scopes don't use find() method in each statement.

$user = User::find(1);

then

$user->hair_color_name;
$user->nationality_name;
  • Related