Martian.titan
Martian.titan

Reputation: 466

Laravel table relationship for getting user list

I'm working on a laravel 5 application. I have 3 tables:

table A: 'users' 

id   |    name
————————————————
1    |    Dave
2    |    Robet
3    |    Jimmy
4    |    Daniel

and Table B classroom_users

user_id | classroom_id 
1       | 5            
4       | 5            
3       | 6  
4       | 5          

I need to return all users 'name' for classroom 5

Please let me know what is the best way to do that. Trough model or Database join

Any help appreciated.

Upvotes: 0

Views: 136

Answers (2)

jaysingkar
jaysingkar

Reputation: 4435

Assuming you have models and its relationships will be defined as below:

Classroom Model:

public function users(){
    return $this->belongsToMany(User::class,'classroom_users','classroom_id','user_id');
}

User Model:

public function classrooms(){
    return $this->belongsToMany(UserClassrooms::class,'classroom_users','user_id','classroom_id');
}

Now, in controller you can retrieve the users belonging to the classroom id 5 as below:

$classroom_id = 5 ;//change this to the id you want
$users = Classroom::find($classroom_id)->users()->get();

Upvotes: 1

anwerj
anwerj

Reputation: 2488

Laravel has introduced Pivot tables, which works like this

 return $this->belongsToMany('App\Role')->withPivot('column1', 'column2');

You can read more pivot on Official Docs

Upvotes: 0

Related Questions