Laravel4: Checking many-to-many relationship attribute even when it does not exist

Posted by Simo A. on Stack Overflow See other posts from Stack Overflow or by Simo A.
Published on 2013-10-19T15:34:33Z Indexed on 2013/10/19 21:56 UTC
Read the original article Hit count: 177

Filed under:
|

This is my first time with Laravel and also Stackoverflow...

I am developing a simple course management system. The main objects are User and Course, with a many-to-many relationship between them. The pivot table has an additional attribute, participant_role, which defines whether the user is a student or an instructor within that particular course.

class Course extends Eloquent {
  public function users() {
    return $this->belongsToMany('User')->withPivot('participant_role')->withTimestamps();
  }
}

However, there is an additional role, system admin, which can be defined on the User object. And this brings me mucho headache. In my blade view I have the following:

@if ($course->pivot->participant_role == 'instructor') {
  // do something here...
}

This works fine when the user has been assigned to that particular $course and there is an entry for this user-course combination in the pivot table.

However, the problem is the system administrator, who also should be able to access course details. The if-clause above gives Trying to get property of non-object error, apparently because there is no entry in the pivot table for system administrator (as the role is defined within the User object).

I could probably solve the problem by using some off-the-shelf bundle for handling role-based permissions. Or I could (but don't want to) do something like this with two internal if-clauses:

if (!empty($course->pivot)) {
  if ($course->pivot->participant_role == 'instructor') {  
    // do something...
  }
}

Other options (suggested in partially similar entries in Stackoverflow) would include 1) reading all the pivot table entries to an array, and use in_array to check if a role exists, or even 2) SQL left join to do this on database level.

However, ultimately I am looking for a compact one-line solution? Can I do anything similar to this, which unfortunately does not seem to work?

if (! empty ($course->pivot->participant_role == 'instructor') ) {
  // do something...
}

The shorter the answer, the better :-). Thanks a lot!

© Stack Overflow or respective owner

Related posts about php

Related posts about laravel