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

tyteck's avatar

Migration and update one table column from another table column

Hi there

The query I need to do is quite simple the MySQL way.

update table1, table2 set table1.column1 = table2.column8 where table1.id=table2.foreign_key

But I would like to do the same query using Laravel Eloquent model ? How do you do this ?

0 likes
1 reply
tyteck's avatar
tyteck
OP
Best Answer
Level 8

I found my own answer so here it is

DB::table('table1')->join('table2', 'table1.id', '=', 'table2.foreign_key')->update(['table1.column1'=>DB::raw('table2.column8')]);

A little bit of context here. I had 2 tables that were joined with a string column. That was a bad idea.

So I added a autoincrement id in the table 2. Then I added a numeric column to table 1. All I had to do was to report the numeric id from table 2 in table 1 on the old join to do the trick.

I searched on many posts here and on stack without finding a solution approching. This one is a mix that is pretty clear.

If you need more information please ask :)

5 likes

Please or to participate in this conversation.