Hello! Today, we are going to talk about one of the useful features of Laravel 11, which can assist us in easily adding initial data to our database. This feature is called Seeder. Seeders are pieces of code that allow us to create predefined records in our database tables. This helps us to effectively utilize test and display databases and facilitate the development of our applications.
By using the command named SeederMakeCommand in this version of Laravel, we can easily create new Seeders. In fact, this command provides us the ability to quickly create Seeder files and update their content. This feature is particularly useful when we have a large number of models and data to work with; it is very handy.
So how can we use this command? First, you need to execute the command line on your Laravel project to run this command. In fact, by executing a simple command, Laravel will generate a new Seeder file for us that we can then define records in that table. However, this file is usually created in the directory database/seeders.
Let's take a look at the structure of this file once we execute this command. When this command is executed, a new class is created that we need to implement the run() method in. In this method, we define everything that we want to add to the database. Subsequently, we can easily run this Seeder through another command to add data to the database.
php artisan make:seeder UserSeeder
This command will create a Seeder file named UserSeeder for you. Now, let’s take a look at the content of this file and see how we can fill it out.
namespace Database\Seeders;
use Illuminate\Database\Console\Seeds\Seeder;
use Illuminate\Support\Facades\DB;
class UserSeeder extends Seeder
{
public function run()
{
DB::table('users')->insert([
['name' => 'Ali', 'email' => 'ali@example.com'],
['name' => 'Sara', 'email' => 'sara@example.com'],
]);
}
}
Code Explanation
Code:
php
Namespace Extraction: This line defines the namespace for the Seeder file that is placed in the directory Database/Seeders.
Seeder Class: This line identifies that the UserSeeder class is inherited from the Laravel Seeder class.
Run() Method: In this method, we are utilizing DB to insert records into the users table.
Inserting Data: Here, we are defining two new records with names and emails that will be added to the users table.