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

846 Views Asked by At

Call to undefined method App\Models\User::attachRole() I'm absolute beginner with laravel I'm using "laratrust" package when I'm trying to register it gives me this error and I don't know why

`<?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');
    }
}
`
1

There are 1 best solutions below

0
On

You dont have any atachRole method in your User model. So it seem's you have missed step #4 of installation section.

Add the Laratrust\Contracts\LaratrustUser interface and Laratrust\Traits\HasRolesAndPermissions trait in your user classes ( normally 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 )

    // ...
}