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

Kabir's avatar
Level 1

Need help to create relation in another eloquent relationship.

Suppose i have 3 tables,

tickets(id,name,user_id,...) users(id,username,company_id) companies(id,name,...)

When i'm trying to get ticket lists, i'm using following function in model Ticket.php

public function user_company(){
        return $this->belongsTo('App\Models\User','user_id','id');
}

It's returning company_id. But how can i get companies.name using same function?

0 likes
3 replies
bobbybouwmann's avatar
Level 88

This relation only fetch the user and not the company. For that you need two relations

// Ticket

public function user()
{
    return $this->belongsTo('App\Models\User', 'user_id', 'id');
}

// User

public function company()
{
    return $this->belongsTo('App\Models\Company', 'company_id', 'id');
}

Now you can fetch both relations

$tickets = Ticket::with('user.company')->get();

foreach($tickets as $ticket) {
    echo $ticket->user->name;
    echo $ticket->user->company->name;
}

This is basic relationship stuff in Laravel. I would recommend you to take another look at the documentation and use the example used there ;)

Documentation: https://laravel.com/docs/5.5/eloquent-relationships

Kabir's avatar
Level 1

I'm a new learner. I had some confusion about this relationship. It's okey now. Thank you so much. :-)

Please or to participate in this conversation.