2016-10-04 110 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

相關問題