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

noop's avatar
Level 5

Get single model from relation with pivot table

I have 3 tables "users", "companies" and the pivot table "company_user". For now a user has to a single company I have a relation in User model called companies() that is a "belongsToMany" this return a collection of companies but I want to have a relation called company that returns a single company model, I can achieve this using a custom query but maybe there are any method provided by laravel framework that can helping me with that.

Any ideas how to achieve this?

0 likes
2 replies
noop's avatar
Level 5

Yes first() will work but I'm trying to do it using eloquent relations to easily do things like $user->company or $user->company()->exists().

I think I found a alternative using hasOneThrough, in User model I can do this

$this->hasOneThrough(Company::class, CompanyUser::class, 'user_id', 'id', 'id', 'company_id');

Please or to participate in this conversation.