BigJobbies
BigJobbies

Reputation: 4033

Laravel using accessor to return a country name from country code

I have a table that has country_code and country_name.

Each user in my database has country_code on their account. What I want to do is automatically return the country_name instead of the country_code for that user.

I have setup an accessor in my User model, but it doesn't seem to work.

public function getCountryCodeAttribute($value): string
{
    return Country::firstWhere('country_code', $value)->get('country_name');
}

It keeps still returning the country_code

Any help would be great

Upvotes: 2

Views: 1276

Answers (1)

mrhn
mrhn

Reputation: 18916

You are working with an QueryBuilder() that returns your model. To access a property on the model, simply access it as it was an property.

return Country::firstWhere('country_code', $value)->country_name;

For exposing it for your endpoint, use the User model append property, where you can add custom Eloquent Setters to the serialization.

class User {
    protected $appends = [
        'country_code',
    ];
}

Upvotes: 2

Related Questions