Call to undefined method Illuminate\Database\Query\Builder::attachRole()

291 Views Asked by At

When I create a user and try to attach roles to it, I get the error cited below. How can I fix the code?

Call to undefined method Illuminate\Database\Query\Builder::attachRole()

    public function store(Request $request)
            {
                 $this->validate($request,[
                    'name' => 'required',
                    'email' => 'required|email|unique:users,email',
                    'password' => 'required|same:confirm-password',
                    'image'=>'required|image|mimes:png,jpg,jpeg|max:1000',
                    'roles' => 'required',
                ]);
                $input=$request->all();
                $input['password'] = Hash::make($input['password']);
                if($request->file('image')){
                    $image=$request->file('image');
                    if($image->isValid()){
                        $fileName=time().'-'.str_slug($input['name'],"-").'.'.$image->getClientOriginalExtension();
                        $image_path=public_path('profile/'.$fileName);
                        //Resize Image
                        Image::make($image)->save($image_path);
                        $input['image']=$fileName;
                    }
                }
                $user = User::create($input);
                foreach ($request->input('roles') as $key => $value) {
                    $user->attachRole($value);
                }
                flashy()->success('User created successfully!');
                return redirect()->route('users.index');

            }
2

There are 2 best solutions below

0
djunehor On

The problem obviously is that you're calling a method on user model which you haven't defined. Whichever role-permission package you're using should give you a Trait to add to your User model.

If you're using spatie role permission package, add use HasRoles; to your User model so the Trait methods can be available to your User Model.

Further details can be found here https://docs.spatie.be/laravel-permission/v3/basic-usage/basic-usage/

1
Mahmoud Nizar On

put in User model ( use LaratrustUserTrait; )