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

afoysal's avatar

Table name in output of Join() query

I have a Query like below. I am outputting json response.

$users = DB::table('users')
            ->join('contacts', 'users.id', '=', 'contacts.user_id')   // need table name as object key here
            ->select('users.*', 'contacts.phone', 'orders.price')
            ->get();
0 likes
6 replies
staudenmeir's avatar

You want the result to be like $user->contact?

1 like
afoysal's avatar

Thanks @staudenmeir . No, I need below output

"contacts": {
     "id": 1,
     "employee_id": 1,
     "text": "good",
     "employee": "Jamal"
}
staudenmeir's avatar

You should use models and relationships:

class User extends Model {
    public function contacts() {
        return $this->hasMany(Contact::class);
    }
}

class Contact extends Model {}

$users = User::with('contacts')->get();
1 like
afoysal's avatar

Thanks @staudenmeir . I have join query like below

->join('employee', function ($join) {
                $join->on('company.surah_id', '=', 'employee.surah_id');
                $join->on('company.verse_id', '=', 'employee.ayah_id');
            }) 

I have a field text in employee table. I would like to fetch certain amount of character. More over I would like to fetch like below

"employee": {
     "text": "Jamal"
} 

staudenmeir's avatar

This case is trickier. Laravel doesn't support relationships with composite keys.

You can use this package: https://github.com/topclaudy/compoships

Or you change the result manually:

foreach($companies as $company) {
    $company->employee = ['text' => $company->text];
}

Please or to participate in this conversation.