Laravel Laravel
  • Prologue

    • Release Notes
    • Upgrade Guide
    • Contribution Guide
  • Getting Started

    • Installation
    • Configuration
    • Directory Structure
    • Frontend
    • Starter Kits
    • Deployment
  • Architecture Concepts

    • Request Lifecycle
    • Service Container
    • Service Providers
    • Facades
  • The Basics

    • Routing
    • Middleware
    • CSRF Protection
    • Controllers
    • Requests
    • Responses
    • Views
    • Blade Templates
    • Asset Bundling
    • URL Generation
    • Session
    • Validation
    • Error Handling
    • Logging
  • Digging Deeper

    • Artisan Console
    • Broadcasting
    • Cache
    • Collections
    • Contracts
    • Events
    • File Storage
    • Helpers
    • HTTP Client
    • Localization
    • Mail
    • Notifications
    • Package Development
    • Queues
    • Rate Limiting
    • Task Scheduling
  • Security

    • Authentication
    • Authorization
    • Email Verification
    • Encryption
    • Hashing
    • Password Reset
  • Database

    • Getting Started
    • Query Builder
    • Pagination
    • Migrations
    • Seeding
    • Redis
  • Eloquent ORM

    • Getting Started
    • Relationships
    • Collections
    • Mutators / Casts
    • API Resources
    • Serialization
    • Factories
  • Testing

    • Getting Started
    • HTTP Tests
    • Console Tests
    • Browser Tests
    • Database
    • Mocking
  • Packages

    • Breeze
    • Cashier (Stripe)
    • Cashier (Paddle)
    • Dusk
    • Envoy
    • Fortify
    • Homestead
    • Horizon
    • Jetstream
    • Mix
    • Octane
    • Passport
    • Pint
    • Sail
    • Sanctum
    • Scout
    • Socialite
    • Telescope
    • Valet
  • API Documentation
  • Introduction
  • Writing Seeders
    • Using Model Factories
    • Calling Additional Seeders
    • Muting Model Events
  • Running Seeders

Database: Seeding

  • Introduction
  • Writing Seeders
    • Using Model Factories
    • Calling Additional Seeders
    • Muting Model Events
  • Running Seeders

Introduction

Laravel includes the ability to seed your database with data using seed classes. All seed classes are stored in the database/seeders directory. By default, a DatabaseSeeder class is defined for you. From this class, you may use the call method to run other seed classes, allowing you to control the seeding order.

Note
Mass assignment protection is automatically disabled during database seeding.

Writing Seeders

To generate a seeder, execute the make:seeder Artisan command. All seeders generated by the framework will be placed in the database/seeders directory:

php artisan make:seeder UserSeeder

A seeder class only contains one method by default: run. This method is called when the db:seed Artisan command is executed. Within the run method, you may insert data into your database however you wish. You may use the query builder to manually insert data or you may use Eloquent model factories.

As an example, let's modify the default DatabaseSeeder class and add a database insert statement to the run method:

<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;

class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeders.
     *
     * @return void
     */
    public function run()
    {
        DB::table('users')->insert([
            'name' => Str::random(10),
            'email' => Str::random(10).'@gmail.com',
            'password' => Hash::make('password'),
        ]);
    }
}

Note
You may type-hint any dependencies you need within the run method's signature. They will automatically be resolved via the Laravel service container.

Using Model Factories

Of course, manually specifying the attributes for each model seed is cumbersome. Instead, you can use model factories to conveniently generate large amounts of database records. First, review the model factory documentation to learn how to define your factories.

For example, let's create 50 users that each has one related post:

use App\Models\User;

/**
 * Run the database seeders.
 *
 * @return void
 */
public function run()
{
    User::factory()
            ->count(50)
            ->hasPosts(1)
            ->create();
}

Calling Additional Seeders

Within the DatabaseSeeder class, you may use the call method to execute additional seed classes. Using the call method allows you to break up your database seeding into multiple files so that no single seeder class becomes too large. The call method accepts an array of seeder classes that should be executed:

/**
 * Run the database seeders.
 *
 * @return void
 */
public function run()
{
    $this->call([
        UserSeeder::class,
        PostSeeder::class,
        CommentSeeder::class,
    ]);
}

Muting Model Events

While running seeds, you may want to prevent models from dispatching events. You may achieve this using the WithoutModelEvents trait. When used, the WithoutModelEvents trait ensures no model events are dispatched, even if additional seed classes are executed via the call method:

<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;

class DatabaseSeeder extends Seeder
{
    use WithoutModelEvents;

    /**
     * Run the database seeders.
     *
     * @return void
     */
    public function run()
    {
        $this->call([
            UserSeeder::class,
        ]);
    }
}

Running Seeders

You may execute the db:seed Artisan command to seed your database. By default, the db:seed command runs the Database\Seeders\DatabaseSeeder class, which may in turn invoke other seed classes. However, you may use the --class option to specify a specific seeder class to run individually:

php artisan db:seed

php artisan db:seed --class=UserSeeder

You may also seed your database using the migrate:fresh command in combination with the --seed option, which will drop all tables and re-run all of your migrations. This command is useful for completely re-building your database. The --seeder option may be used to specify a specific seeder to run:

php artisan migrate:fresh --seed

php artisan migrate:fresh --seed --seeder=UserSeeder 

Forcing Seeders To Run In Production

Some seeding operations may cause you to alter or lose data. In order to protect you from running seeding commands against your production database, you will be prompted for confirmation before the seeders are executed in the production environment. To force the seeders to run without a prompt, use the --force flag:

php artisan db:seed --force
last update:2022-10-07 14:30

成为Laravel合作伙伴

Laravel Partners是提供一流Laravel开发和咨询服务的精英商店。我们每个合作伙伴都可以帮助您制定一个精美,结构完善的项目.

我们的伙伴
Laravel
亮点
  • Our Team
  • Release Notes
  • Getting Started
  • Routing
  • Blade Templates
  • Authentication
  • Authorization
  • Artisan Console
  • Database
  • Eloquent ORM
  • Testing
资源
  • Laracasts
  • Laravel News
  • Laracon
  • Laracon EU
  • Jobs
  • Certification
  • Forums
  • 版本发布时间
  • 包开发
  • 命令行应用
  • TALL stack全栈开发
  • Blade UI Kit
  • 前端资源构建
伙伴
  • Vehikl
  • Tighten Co.
  • Kirschbaum
  • Byte 5
  • 64 Robots
  • Cubet
  • DevSquad
  • Ideil
  • Cyber-Duck
  • ABOUT YOU
  • A2 Design
  • Romega Software
  • Jump24
  • Become A Partner
生态系统
  • Cashier
  • Dusk
  • Echo
  • Envoyer
  • Forge
  • Homestead
  • Horizon
  • Lumen
  • Mix
  • Nova
  • Passport
  • Scout
  • Socialite
  • Spark
  • Telescope
  • Valet
  • Vapor

Laravel是一个具有表达力,优雅语法的Web应用程序框架。我们认为,发展必须是一种令人愉悦的创造力,才能真正实现。Laravel试图通过减轻大多数Web项目中使用的常见任务来减轻开发的痛苦.

Laravel是Taylor Otwell的商标.
Copyright © 2011-2022 Laravel中文网 LLC.

  • Twitter
  • GitHub
  • Discord
Laravel PHP中文网 推荐使用阿里云