Yad Hoshyar
Yad Hoshyar

Reputation: 43

laravel many to many relationship get data from pivot table

I have a many to many relationship between between User and Classroom Models

this is the structure:

- users
  - id
  - name

- classroom_user
   - classroom_id
   - user_id
   - is_teacher

- classrooms
  - id
  - name

this is the relationships:

user model:

public function classrooms() {
    return $this->belongsToMany(Classroom::class)->withPivot('is_teacher');
}

classroom model:

public function users() {
    return $this->belongsToMany(User::class)->withPivot('is_teacher');
}

public function teachers() {
    return $this->belongsToMany(User::class)->where('is_teacher','=',1);
}

public function students() {
    return $this->belongsToMany(User::class)->where('is_teacher','=',0);
}

I want to check if current logged in user is a teacher in current classroom or not by obtaining the value of is_teacher column.

currently doing it this way:

auth::user()->classrooms->find($classroom->id)->pivot->is_teacher

is there a better way to do this?

Upvotes: 1

Views: 1202

Answers (1)

Luis Montoya
Luis Montoya

Reputation: 3207

I would just do it like this to avoid issues in case the classroom does not exist:

$classroom = auth::user()->classrooms()->find($classroom->id);
if (! $classrooom) {
   // throw/return an error accordingly
} 
$isTeacher = $classrooom->pivot->is_teacher

PS: Doing classrooms with parenthesis is extremely important, otherwise you are returning all the classrooms that belong to the user and doing the filtering in the PHP side.

Upvotes: 2

Related Questions