Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

falke2's avatar

Laravel 9 relation and attribute conflict

Hello. Before Laravel 9 came out i was using relations and attributes this way (just an example):

public function countries(): \Illuminate\Database\Eloquent\Relations\BelongsToMany
{
    return $this->belongsToMany(Country::class);
}

public function getCountriesAttribute(): \Illuminate\Http\Resources\Json\AnonymousResourceCollection
{
    return CountryResource::collection($this->countries);
}

Now i have to name such accessor/mutator as country(): Attribute but i have relation method with same naming. Is there any elegant case except renaming relation country() to countryRelation()?

0 likes
7 replies
Nakov's avatar

I don't think you have to as this getCountriesAttribute will still work.

falke2's avatar

@Nakov yeah but i wanted to use this new syntax in all of the models and it hurts me when i use both approaches in single project.

Sinnbeck's avatar

@falke2 You cannot have two methods with the same name. Simple as that :) And I think the feature is so new, that there haven't been written any best practice guides yet. But personally add resources inside the model anyways :)

Sinnbeck's avatar

@falke2 Ok thats totally fine :) But you will need to have some distiction between attributes and relationships. Personally I would make so anyways, as I don't like not being 100% sure what I am working with

falke2's avatar

@Sinnbeck yeah i'm gonna keep naming clear. Let's see how laravel devs gonna handle it. If they will of course :)

siamak-s's avatar

Consider the following trait that could be used inside Eloquent models:

github.com/rinvex/laravel-bookings/blob/master/src/Traits/Bookable.php [Sorry I could not post links for the first day of sign up]

We can not achieve the above functionality with the new Mutator convention for Laravel 9. Because the relation method (e.g. bookings) has conflicts with the new form of mutators bookings(): Attribute.

Any idea to achieve the above functionality with the new mutator convention inside Laravel 9?

Please or to participate in this conversation.