0

Trying to duplicate one column to another on MySQL using Laravel 8, the statement runs but values are not persisted.

DB::statement('UPDATE posts SET title = previous_title;');

Is there any solution to handle this case?

1 Answers1

-1

DB uses your default database connection from config/database.php DB credentials are mostly set in .env file.

When you use

DB::statement('UPDATE ....

the table is not specified anywhere and therefore it doesn't know on which table you want to make that update.

Solution 1

Use this to specify the table

DB::table('table_name')->statement('UPDATE ....

Solution 2

Use Eloquent because the table is set behind the scenes

User::update('column_name', NEW_ VALUE);

Have in mind this will update all rows on that table with same value if you don't use WHERE clause

lewis4u
  • 14,256
  • 18
  • 107
  • 148
  • I'm not sure if Eloquent can be used because I am getting error 'Non static method 'update' should not be called statically.' – Prem Arumugam Oct 29 '21 at 07:14
  • DB::statement executes arbitrary raw SQL (w/ bindings). You do not specify a table when using it (other than in the query directly). DB::statement('SELECT NOW()') is perfectly valid. So is DB::statement("SELECT * FROM users'). That is also not the correct way to update a model using eloquent. – Steven W Sep 30 '22 at 18:47