2013-08-02 44 views
0

我跟着http://laravel.com/docs/一些教程,它只是不会工作。下面是我的尝试:Laravel错误调用成员函数

榜样:

<?php 

class Role extends Eloquent { 

    protected $table = 'accounts'; 

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

RoleController.php

<?php 

class RoleController extends BaseController { 

    public function get_role() 
    { 
     $roles = User::find(16)->group_id; 

     if ($roles->contains(3)) 
     { 
      echo 'this works'; 
     } 
     else 
     { 
      return Redirect::to('news/index'); 
     } 
    } 
} 

我的路线:

Route::get('dash', '[email protected]_role'); 

这是我的错误:

Call to a member function contains() on a non-object 

它说的错误是路线:

if ($roles->contains(3)) 

像contains方法是...我不知道哈。

另外,$roles = User::find(16)->group_id; 16是id的帐户,对不对?而group_id是表?

在此先感谢。

编辑:

这里的解决方案,我在RoleController.php改变了它:

<?php 

class RoleController extends BaseController { 

    public function get_role() 
    { 
     $roles = User::find(16)->group_id; 

     if (if ($roles == '1') 
     { 
      echo 'this works'; 
     } 
     else 
     { 
      return Redirect::to('news/index'); 
     } 
    } 
} 
+0

做'的print_r($角色)',看看你 – naththedeveloper

+0

我做了这样的内容:'类RoleController扩展BaseController { \t公共职能get_role(){$ 角色=用户::发现(16 ) - > GROUP_ID; print_r($ roles); } }'它只显示1:p 另外我尝试使用包含方法将其设置为1,但它仍然会出现该错误。 – dinomuharemagic

+0

你的脚本期望'$ roles'是一个对象,如你的调试所示,'$ roles'包含'1'(不是一个对象),这就是为什么你会得到这个错误。 – naththedeveloper

回答

1

这条线:

$roles = User::find(16)->group_id; 

意味着你在问:“找到用户16,并给我该用户的group_id“。这是你引用的“1”(在你的评论中)。

既然你已经在group_id - 变化

if ($roles->contains(3)) 

if ($roles == '3') 
0

这里的解决方案,我在RoleController.php改变了它:

<?php 

类RoleController扩展BaseController {

public function get_role() { 
$roles = User::find(16)->group_id; 

      if (if ($roles == '1') 
      { 
       echo 'this works'; 
      } else { 

       return Redirect::to('news/index'); 
        } 
      } 
} 
+0

你可以更新你的答案,包括*你在哪里*你改变代码?一个更大的片段(我知道你可以通过阅读这个问题来推论,但如果答案是自给自足的话会更好) – Nunser

相关问题