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

lavina's avatar

Laravel eloquent connecting multiple tables

Hello guys, i am attempting to make a select from and combine 3 tables into one:

class SectionAndUser
    public function sections()
    {        return $this->belongsTo('App\Models\Section');}
    public function users()
    {return $this->belongsTo('App\Models\User');}
class User 
    public function sectionAndUser(){return $this->hasMany('App\Models\SectionAndUser');}
class Section
    public function section_and_users(){return $this->hasMany('App\Models\SectionAndUser');}

These are the 3 models and their relationships, i would like to select starting from user all the sections he belongs to and then get the remaining info from the table sections. With the select:$sections = User::find($userId)->sectionAndUser()->get(); i get the result:

     "id": 1,
     "section_id": 1,
     "user_id": 133
 },

How do i now connect it with the sections table and pick up section name based on the section_id?

0 likes
6 replies
abhi321's avatar

just use the relation table function name eg echo $section->section->name of the table

lavina's avatar

Not sure what you mean @abhi321, i am trying to create a join using elequent models, so i would like to keep it in 1 line, there will be a lot of these and multiple joins later on as well.

Sql would be something like:

    $id=Auth::id();
    $results = DB::table('sections')
        ->join('section_and_users', function ($join) use ($id) {
            $join->on('sections.id', '=', 'section_and_users.section_id')
                ->where('section_and_users.user_id','=', $id);
        })
        ->get();
bony's avatar

i think this will help you..

        UserTest::join('tests', 'tests.id', '=', 'user_tests.test_id')

                    ->select(DB::raw('count(*) as count,tests.*')) 

                    ->groupBy('user_tests.test_id')

                    ->orderBy('count','desc') 

                    ->take(10)

                    ->get();
abhi321's avatar

i am trying to say you want display the name relavent to section id right so just use the $section-> section_and_users->section table name and give me the output

Please or to participate in this conversation.