I have 3 Models in My Laravel App like Employee , Salary and Title. Employee Model one to Many Relationship with both Salary and Title Models. Now I need update data using EmployeeController updateEmployee function
EmployeeController
public function updateEmployee(Request $request, $id) {
$employee = Employee::find($id);
$title = $employee->titles()->update($request->all);
$salary = $employee->salaries()->update($request->all);
if(is_null($employee)) {
return response()->json(['message' => 'Employee not found'], 404);
}
$employee->update($request->all());
return response($employee, 200);
}
and my api route is following
Route::put('updateEmployee/{id}','AppHttpControllersEmployeeController@updateEmployee');
Employee Model
public function titles(): HasMany
{
return $this->hasMany(Title::class, 'emp_no');
}
public function salaries(): HasMany
{
return $this->hasMany(Salary::class, 'emp_no');
}
}
Salary Model
public function employee(): BelongsTo
{
return $this->belongsTo(Employee::class, 'emp_no');
}
Title Model
public function employee(): BelongsTo
{
return $this->belongsTo(Employee::class, 'emp_no');
}
but when I try update I got following error message
TypeError: IlluminateDatabaseEloquentBuilder::update(): Argument #1 ($values) must be of type array, null given, called in F:2023code2023apivendorlaravelframeworksrcIlluminateSupportTraitsForwardsCalls.php on line 23 in file F:2023code2023apivendorlaravelframeworksrcIlluminateDatabaseEloquentBuilder.php on line 1009
how could I fix this matter?
2
Answers
The error indicaties that you don’t send any data to your API. (
$request->all()
is null).That is because you don’t verify if the requests contains any data.
You can validate the request using the
$request->validate()
method. More info about that in the Laravel docs;Alternatively you can use Laravel form requests.
your data is null. check your route api. pass in your variable by array.