0

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!

4

2 回答 2

0

我倾向于创建一个检查数据透视表值以及用户是否具有系统管理员访问权限的访问器然后使用该访问器进行您的权限检查,而不是您视图中的全部内容。

我不太确定你是如何布置信息和视图的,将用户逻辑注入到课程模型中可能不是最好的主意,所以你在哪里以及如何精确地布置访问器不是我能做到的自信地明确建议。但它可能会让你走上正轨。

于 2013-10-20T01:04:03.787 回答
0

我真的不认为有一个完美的方法来做到这一点。您可以尝试其中一种:

一个如果,&&运算符

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

尽管这几乎是您不想在一个中执行的两个 if已经是真的了。

错误控制运算符(不推荐)

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

这可能是最短且更好看的解决方案,但并不真正推荐。运算符的使用会@抑制任何错误,包括关键错误,减慢代码速度,并可能在以后调试代码时带来意想不到的麻烦。

于 2013-10-19T21:44:26.010 回答