bfinlay / laravel-excel-seeder

Seed your database with Laravel using Excel and CSV files
Other
38 stars 8 forks source link

Pass data into a seed class #31

Open raarevalo96 opened 1 month ago

raarevalo96 commented 1 month ago

Hello there. Thank you for creating and maintaining this super useful package. I have a question on if (and if it's possible, how) I can achieve something.

Say that I want to create a SpreadsheetSeeder that can receive data and use it as default. For this example, I will use fictional models Warehouse and Product, since I don't want to disclose the exact logic behind this.

The README says:

Create a seed class that extends bfinlay\SpreadsheetSeeder\SpreadsheetSeeder and configure settings on your class.

I created a new seed class (let's call it DefaultProductSeeder) that defines a custom setting set with a specific file, some parsers and defaults. Say that I want to reuse this Seeder programatically to seed a table upon another model creation, (say, in the WarehouseController), I want to automatically use the ProductSeeder to associate some default products).

On a normal seeder, I can achieve this by doing something like this:

class DefaultProductSeeder extends Seeder
{
    public function run(Warehouse $warehouse): void
    {
        Product::factory()->create([
            "warehouse_id" => $warehouse->id
        ]);
    }
}

And then I can run the seeder inside a Controller by doing this:

    $warehouse = Warehouse::create(["name" => "Test Warehouse"]);
    $seeder = new DefaultProductSeeder();
    $seeder->run($warehouse);

I've tried many ways of doing this with a custom Seeder class that extends SpreadsheetSeeder, but so far I've been unable to do so. The README also says:

note: the older process of overloading run() still works for backwards compatibility.

This gives me a hint that maybe I can achieve something like this. But right now, the only way I can get to work to run my custom Seeder is inside another seeder via the call() method, and a $warehouse already defined as a default.

Thank you in advance for your help.

I'm using Laravel 11.16.0 with PHP 8.2.19.

bfinlay commented 3 weeks ago

This is an interesting use case. I would have liked to start looking into it sooner.

This is similar to issue #23, except that what you want to pass the warehouse as a parameter.

I think to do that I need to refactor the code a bit. Currently the SpreadsheetSeeder class introduces a run method and that prevents subclasses from changing the signature. I may possibly need to introduce an abstractSpreadsheetSeeder class so that you can provide a run method that accepts parameters.

I will look into it some more.