-1

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');

            }
Michael Karcher
  • 3,803
  • 1
  • 14
  • 25
Vit IT
  • 1

2 Answers2

1

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/

djunehor
  • 941
  • 7
  • 9
0

put in User model ( use LaratrustUserTrait; )

  • Hi @Mahmoud Nizar, Please be more specific when giving answers and try to explain the solution and the reason that caused the problem – skm Sep 13 '20 at 12:31