Call to undefined method App\Models\User::attachRole() error
P粉418351692
2023-08-30 14:08:49
<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>
You don't have any
atachRole
method in your User model. So it seems you missed step 4 of the Installation section.Add the
Laratrust\Contracts\LaratrustUser
interface and theLaratrust\Traits\HasRolesAndPermissions
trait to your user class (usually located in App\Models\User).