Home > Software design >  Method Illuminate\Database\Eloquent\Collection::salarylevels does not exist
Method Illuminate\Database\Eloquent\Collection::salarylevels does not exist

Time:06-13

I have a many to many relationship between users and salary_levels. All I have is an error stating Method Illuminate\Database\Eloquent\Collection::salarylevels does not exist. The salarylevels method is defined under User model. How could this happen?

User Model:

 public function salarylevels(){
   
    return $this->belongsToMany(SalaryLevel::class)->withPivot(['leave_entitlement']);

   }

SalaryLevel:

 public function users(){

  return $this->belongsToMany(User::class)->withPivot(['leave_entitlement']);

}

Store Method:

public function store(Request $request) {
    
    $users = User::where('id',$request->input('employee_id', []))->get();

    
    $Ids = [
       1 => ['leave_entitlement' => '30'],
       3 => ['leave_entitlement' => '22']
     ];

    $users->salarylevels()->sync($Ids);

}

CodePudding user response:

Your issue is that $users->salaryLevels() is not correct. $users is a Collection because you have done:

$users = User::where('id', $request->input('employee_id', []))->get();

get() returns a Collection, so you should do:

$users = User::where('id', $request->input('employee_id', []))->first();
  • Related