Search code examples
sqllaravellaravel-artisan

Laravel update database record running script


I want to update any records in my database running SQL script using artisan. For example, I need to execute such command:

UPDATE translations SET field = 'meta_desc' WHERE field = 'page_desc'

What the Laravel's sctructure will be the best solution? Seed, migrations, factories?


Solution

  • Thanks to everybody for replies. Ecpesially thanks to @RossWilson for his idea of using migrations for changing DB's data.

    But I think, it's not a good solution, because the Laravel's concept involves using migrations for DB structure's changing.

    After reading Laravel's manuals I've found that there is a special code structure for working with db's data. It's a Seed. So, I solved my issue using the next seed for my example query above:

    1. Created the new seed using artisan command:

      php artisan make:seed UpdateTranslationsSeeder
      
    2. Write a code inside the run() method:

      DB::table('translations')->where('field', 'page_desc')->update(['field' => 'meta_desc']);
      
    3. Run my seeder in artisan:

      php artisan db:seed --class=UpdateTranslationsSeeder
      

    Note: if after running the last command in console I've got an error about class UpdateTranslationsSeeder is undefined run the next command in console to tell Laravel about new classes:

    composer dump-autoload -o