Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Amalmax's avatar

How to Update Laravel elaquent tables using one Controller function

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}','App\Http\Controllers\EmployeeController@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 Illuminate\Database\QueryException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'first_name' in 'field list' (SQL: update titlessetfirst_name= kevin,salary= 90000 wheretitles.emp_no= 10 andtitles.emp_nois not null) in file F:\2023\code\2023\api\vendor\laravel\framework\src\Illuminate\Database\Connection.php on line 760

I need update some time 3 tables data or some time one table data

how could I fix this problem?

0 likes
8 replies
Tray2's avatar

Take a close look at these three lines of code.

$title = $employee->titles()->update($request->all);

$salary = $employee->salaries()->update($request->all);

$employee->update($request->all());

There are so many problems with this code, but let's start with the most dangerous one.

You are sending data from the user directly into the database without validation!!!!

The first line updates the title right? Why are you sending the whole request? That is what gives you the error.

This is probably what you need.

$title = $employee->titles()->update($request->title);

The same goes for the other update,.

$salary = $employee->salaries()->update($request->salary);

The last one you try to update the employe, to make that work you need to tell it which value you want to go into what column, otherwise it will try to insert data into columns that does not exist.

You really should watch the free Laravel 8 from Scratch series here

https://laracasts.com/series/laravel-8-from-scratch

Amalmax's avatar

@Tray2 did you mean using $employee->update($request->all()); is not correct for updating only one column on the employees table?

Tray2's avatar

@Amalmax No, I mean that $request->all() is extremely dangerous, and you must validate your data before inserting it into the database. The validated() method returns an array of the valid date, and then you use that array to update your record in the database. The route should use route model binding.

public function update(Book $book, BookFormRequest $request)
{
   $book->update($request->validated());
    return redirect(route('books.index'));
}

And then you use a FormRequest for your validation

class BookFormRequest extends FormRequest
{
    public function rules(): array
    {
        return [
            'title' => ['required', 'string'],
            'published_year' => [
                'required',
                'numeric',
                'min_digits:4',
                'max_digits:4',
                'between:1800,'.Carbon::now()->addYear(1)->year,
            ],
            'isbn' => ['required', new Isbn()],
            'blurb' => ['required', 'string', new MinWords(3)],
            'author' => ['required', 'array'],
            'genre_name' => ['required', 'string'],
            'format_name' => ['required', 'string'],
            'series_name' => ['required', 'string'],
            'publisher_name' => ['required', 'string'],
            'part' => [
                new RequiredIfNotStandalone($this->series_name),
                new NumericIfNotStandalone($this->series_name),
            ],
        ];
    }

If you don't understand this, I highly suggest that you watch the Laravel From Scratch series here on Laracasts, it's free.

https://laracasts.com/series/laravel-8-from-scratch

Amalmax's avatar

@Tray2 yes I know it is dangerous enter data without validation. I need validate like your sujject. but still I am unable to understand why got above error without updating tables

Tray2's avatar

@Amalmax Because the model is looking for a column that doesn't exist in the table belonging to the model.

Amalmax's avatar

@Tray2 ohhh. Then in this way may I unable to save data to different tables using same controller function?

Tray2's avatar

@Amalmax No, but you need to decide what to update for each model.

$valid = $this->validated()
$model1->update([
	'some_column' => valid['some_column'],
   'some_other_column' => valid['some_other_column]
]);

$model2->update([
	'some_yet_other_column' => valid['some_yet_other_column'],
   'some_fourth_other_column' => valid['some_fourth_other_column]
]);

Please or to participate in this conversation.