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?
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:
Created the new seed using artisan command:
php artisan make:seed UpdateTranslationsSeeder
Write a code inside the run() method:
DB::table('translations')->where('field', 'page_desc')->update(['field' => 'meta_desc']);
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
I have adapted Paul Basenko approach to updating existing data for educational purposes. It was very useful! Here is my example:
Generate a seeder:
php artisan make:seed UpdateCustomerSeeder
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();
});
Run seeder:
php artisan db:seed --class=UpdateCustomerSeeder
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With