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 using this function I need update some time all 3 tables tada also.
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
IlluminateDatabaseQueryException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'first_name' in 'field list' (SQL: update
titlesset
first_name= kevin,
salary= 90000 where
titles.
emp_no= 10 and
titles.
emp_nois not null) in file F:2023code2023apivendorlaravelframeworksrcIlluminateDatabaseConnection.php on line 760
how could I fix this?
2
Answers
The best way u should do is parse your fields and thats it. So in controller you can have smth like this:
and in folder
app/Http/Requests
createPoseCreateRequest.php
i mean create your own name and addand done, now back to controller and as usual in your
$request->all()
you have all fields, but when u make validation so your$request->all()
contains only validate existing fields in request file. even if your request before has 10 fields, after this code u will return onlyyour_fieldname_1
,your_fieldname_1
,captcha