search

Home  >  Q&A  >  body text

Call to undefined method App\Models\User::attachRole() error

<p><blockquote> <p>Call undefined method App\Models\User::attachRole() I'm an absolute beginner with Laravel I'm using the "laratrust" package when I try to register it gives me this error and I don't know why</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粉418351692458 days ago500

reply all(1)I'll reply

  • P粉738346380

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

    You don't have any atachRole method in your User model. So it seems you missed step 4 of the Installation section. < /p>

    Add the Laratrust\Contracts\LaratrustUser interface and the Laratrust\Traits\HasRolesAndPermissions trait to your user class (usually located in 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 )
    
        // ...
    }
    

    reply
    0
  • Cancelreply