Elyton's avatar

How to update already existing seeder in Laravel?

I already have a seeder file that deals with status in the system, how do I register 2 more?

I want to add 2 more statuses below in this file, when I run the file it duplicates the information.

Below is the code

	class StatusSeeder extends Seeder{
		public function run(){
    	 			$names= [
       						 'Status 1',
				             'Status 2,
				            'Status 3',
     	          ];


    		 foreach ($names as $name) {
          				DB::table('status')->insert(['name'=>  $name]);
     		}
       }
   }
0 likes
12 replies
Sinnbeck's avatar

You forgot the code? And you can just add more data to the seeder? But what are you using it for? Testing?

Sinnbeck's avatar

@Elyton so add two more files that seeds what you want then to? I assume you have this one registered in the main seeder? And what do you use them for?

Elyton's avatar

@Sinnbeck Yes, I already have this information from this file in the bank, and I want to add 2 more statuses in that same file and execute the command to register in the bank

I found a solution to update and add the +1 roles in seeder

ex: Role::firstOrCreate(['name' => 'manager-executive']);

And in this file cannot use the same solution using firstOrCreate.

Sinnbeck's avatar

@Elyton let me try again. Is this for testing or for your production database? It makes a huge difference

Sinnbeck's avatar

@Elyton ok. Then for it to work in production, you need to check if those statuses already exist before inserting them. So wrap it in an if statement

Tray2's avatar

@Elyton One easy way to do it is to use firstOrCreate(); in your seeder.

User::firstOrCreate(['name' => 'John Doe']);
1 like
achur00's avatar
 <?php
     //using the firstOrCreate model method
      namespace App\Models;
      namespace Database\Seeders;
      use Illuminate\Support\Facades\DB;
      use App\Models\Status;
      use Illuminate\Database\Seeder;

      class StatusSeeder extends Seeder 
      { 
 public function run()
{
    $names= [
        'Status 1',
     'Status 2',
    'Status 3',
    'Status 4' ];

foreach ($names as $names){
 Status::firstOrCreate(['names'=>$names]);
}
    // foreach ($names as $name) {
 
   // DB::table('status')->insert(['names'=>$name]); 
   
   //     }
 }

}

1 like
achur00's avatar

yes, he did but I wanted to point out that it wont work if

  protected $fillable = 'names'; 

was initialize in the model and will gives the error: "count(): Parameter must be an array or an object that implements Countable." so protected $fillable doesnt need to be use here.

Please or to participate in this conversation.