首页  >  问答  >  正文

调用未定义的方法 App\Models\User::attachRole() 错误

<p><blockquote> <p>调用未定义的方法 App\Models\User::attachRole() 我是 Laravel 的绝对初学者 当我尝试注册时,我正在使用“laratrust”包,它给了我这个错误,我不知道为什么</p> </blockquote> <pre class="brush:php;toolbar:false;">`<?php namespace App\Http\Controllers\Auth; use App\Http\Controllers\Controller; use App\Providers\RouteServiceProvider; use App\Models\User; use Illuminate\Foundation\Auth\RegistersUsers; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Validator; use Laratrust\Traits\HasRolesAndPermissions; class RegisterController extends Controller { use RegistersUsers; use HasRolesAndPermissions; protected $redirectTo = RouteServiceProvider::HOME; public function __construct() { $this->middleware('guest'); } protected function validator(array $data) { return Validator::make($data, [ 'name' => ['required', 'string', 'max:255'], 'email' => ['required', 'string', 'email', 'max:255', 'unique:users'], 'password' => ['required', 'string', 'min:8', 'confirmed'], ]); } protected function create(array $data) { $user = User::create([ 'name' => $data['name'], 'email' => $data['email'], 'password' => Hash::make($data['password']), ])/*->attachRole('user')*/; return $user->attachRole('admin'); } } `</pre></p>
P粉418351692P粉418351692439 天前472

全部回复(1)我来回复

  • P粉738346380

    P粉7383463802023-08-31 09:43:51

    您的 User 模型中没有任何 atachRole 方法。 所以看来您错过了安装部分的第4步。< /p>

    在您的用户类中添加 Laratrust\Contracts\LaratrustUser 接口和 Laratrust\Traits\HasRolesAndPermissions 特征(通常位于 App\Models\User 中)。

    use Laratrust\Contracts\LaratrustUser;
    use Laratrust\Traits\HasRolesAndPermissions;
    use Illuminate\Foundation\Auth\User as Authenticatable;
    
    class User extends Authenticatable implements LaratrustUser // 
    {
        use HasRolesAndPermissions;  // <- This will add some methods and property to your class ( attachRole included )
    
        // ...
    }
    

    回复
    0
  • 取消回复