Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 359
Paul Basenko Avatar asked Jun 29 '17 08:06

Paul Basenko


2 Answers

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
like image 101
Paul Basenko Avatar answered Oct 16 '22 03:10

Paul Basenko


I have adapted Paul Basenko approach to updating existing data for educational purposes. It was very useful! Here is my example:

  1. Generate a seeder:

    php artisan make:seed UpdateCustomerSeeder
    
  2. Add code inside run method:

    $customers = Customer::all();
    
    $customers->each(function ($customer_update, $key) {
        $faker = Factory::create('it_IT');
    
        $customer_update->name = $faker->company;
        $customer_update->website = $faker->domainName;
        $customer_update->tax_number = $faker->vatId();
        $customer_update->phone = $faker->phoneNumber;
        $customer_update->email = $faker->safeEmail;
        $customer_update->street = $faker->streetAddress;
        $customer_update->city = $faker->city;
        $customer_update->zip_code = $faker->postcode;
        $customer_update->notes = $faker->sentence();
    
        $customer_update->save();
    });
    
  3. Run seeder:

    php artisan db:seed --class=UpdateCustomerSeeder
    
like image 30
Matrizlab Avatar answered Oct 16 '22 02:10

Matrizlab