简体   繁体   中英

Laravel 8 Migrations - How can I create instances of a Model, and add it a value, when a database is being created with Migrations?

I am a beginner to Web Development and I am facing an issue with a problem that seems rather simple.

I am trying to insert values immediatly after a database is created with migrations with Laravel 8. This is the my code:

Schema::create('templates', function (Blueprint $table) {
    $table->id();
    $table->string('name')->unique();
    $table->timestamps();

    for ($i = 0; $i != 3; $i++) {
        $template = new Template;
        switch ($i) {
            case 0:
                $template->name = 'Template 1';
                break;
                    
            case 1:
                $template->name = 'Template 2';
                break;
    
            case 2:
                $template->name = 'Template 3';
                break;
        }
    }

});

How can I achieve the result that I want?

First, you're not saving a resource to the database with that code. You're only creating an instance of a Template object and setting the name property. You'd have to call save() on it afterwards to save it to the database.

Try calling your model code outside of (after) your Schema::create call.

Also, this is not part of your question, but you could simplify that create functionality in a number of ways. Here's one:


use Illuminate\Support\Collection; // at the top of the file

...

Schema::create('templates', function (Blueprint $table) {
    $table->id();
    $table->string('name')->unique();
    $table->timestamps();
});

Collection::times(3, fn ($number) => Template::create(['name' => 'Template ' . $number]);

Note

Creating Template objects like this will only work if you have added the name property to the $filllable array for the model, AND if there are no other fields in that table (auto-incrementing primary keys excluded) that require non-null values (obviously not relevant in this case, but something to consider when using mass-assignment).

Here's some more information from the laravel docs:

https://laravel.com/docs/9.x/eloquent#mass-assignment https://laravel.com/docs/9.x/collections#method-times

you should use a constant seeder. see this link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM