2016-10-04 109 views
0

当我尝试在用户注册部分为用户分配角色时,我总是收到找不到方法的错误。在laravel中找不到方法角色Auth

下面是我使用的AuthController

namespace App\Http\Controllers\Auth; 
use Validator; 
use App\Http\Controllers\Controller; 
use Illuminate\Foundation\Auth\ThrottlesLogins; 
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers; 

use Illuminate\Http\Request; 
use Illuminate\Support\Facades\Auth; 

use App\User; 

class AuthController extends Controller 
{ 

protected function create(array $data) 
{ 
    $user = User::create([ 
     'first_name'  => $data['first_name'], 
     'last_name'   => $data['last_name'], 
     'email'    => $data['email'], 


    ])->get(); 

    $user->roles()->sync([2]);  

    return $user; 
} 
} 

下面的代码我的用户模型

namespace App; 

use Illuminate\Foundation\Auth\User as Authenticatable;  
use Zizaco\Entrust\HasRole;  
use App\Role; 

class User extends Authenticatable 
{ 

    /** 
    * The attributes that are mass assignable. 
    * 
    * @var array 
    */ 
    protected $table = 'users'; 
    protected $fillable = [ 
     'first_name','last_name', 'email', 'password' 
    ]; 

    /** 
    * The attributes that should be hidden for arrays. 
    * 
    * @var array 
    */ 
    protected $hidden = [ 
     'password', 'remember_token', 
    ]; 

    public function roles() 
    { 
     return $this->belongsToMany('App\Role'); 
    } 


} 

我不知道为什么会这样。我想也许它没有正确导入User模型,或者我错过了一些东西。我是laravel的新手,所以任何帮助都会受到欢迎。

回答

0

创建模型简单地使用以下命令:

$user = User::create($attributes) 

注意,我没有打电话get()后记。 get()将执行查询返回Collection。我不确定您的Role模型是什么样子,但它现在应该可以正常工作。

+0

我不小心将用户模型文件复制到另一个位置,并且浪费时间试图找出它不工作的原因。这解决了我在实现这个并检查了正确的文件后得到的问题。谢谢。 – user1634781

相关问题