CLOSE

What are Migrations?

Migrations, in the context of Laravel, are essentially version control for your database schema. They allow you to modify the database structure in a structured and organized manner without manually altering the database schema. Migrations are essentially version-controlled files that define changes to your database.

Creating Migration File

Once you have set up your Laravel project, you can create a new migration by running the following command in the terminal:

php artisan make:migration create_posts_table

This will create a new file in the database/migrations directory, with a unique timestamp in the filename to ensure that the order of migrations is preserved. For example: 2024_01_27_create_posts_table.php.

|- app
|--bootstrap
|--config
|--database
   |--migrations
      |--xxxx_xx_xx_xxxxxx_create_posts_table.php

In the file, you will find a class with two methods: up and down. The up method is used changes to the database, while the down method is used to undo those changes.

For example, to create a new table called posts with columns for id, name, description, and content, you would write the following code in the up method:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class () extends Migration {
    public function up(): void
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('name', 255);
            $table->string('description', 400)->nullable();
            $table->longText('content')->nullable();
            $table->timestamps();
        });
    }

};

.. above code

public function down(): void
    {
        Schema::dropIfExists('posts');
    }

Once you have written your migration, you can run it using the following command:

php artisan migrate

This will apply changes to the database and create the posts table. If you need to revert the changes, you can run the following command:

php artisan migrate:rollback

This will undo the last migration and drop the posts table.

Understanding Seeders:

Seeders are PHP classes that allow you to insert predefined data into your database table. They are primarily used to populate the database with the sample data for development, testing, or demo purposes.

Laravel provides a convenient way to define and execute seeders, making it easy to manage and maintain you database content.

Create Seeder File

In order to build the seeder class, you need to run the below command:

php artisan make:seeder PostSeeder

After you run the above command, it will create once file PostSeeder.php in the seeder directory.

 |--root
 	|--database
 		|--migrations
 		|--seeder
 			|--PostSeeder.php

The newly generated PostSeeder.php has the below content:

<?php

namespace Database\Seeders;

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

class PostSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        //
    }
}

In order to generate data for our table, we have to create model for our table.

Generate Model:

To create a new model in Laravel, you can use the artisan command-line tool. Run the below command:

php artisan make:model modelName

Replace modelName with the name of your model. This command will generate a new model file in the app directory of you Laravel project.

For example: for our posts table, we will create a model named as Post. So, we will be running the below command:

php artisan make:model Post
image-47.png

This would create a file Post.php in the directory app/Models which would be as follows:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use HasFactory;
}

we have to modify it to point our posts table i.e., we need to define model properties.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use HasFactory;
    
     // Define the table associated with the model
     protected $table = 'posts';

     // Define mass assignable attributes
     protected $fillable = ['name', 'description', 'content'];
 
     // Define guarded attributes
     protected $guarded = ['id'];

}

Using Model with the Seeder to Generate Data:

Modify the PostSeeder.php which we built before.

<?php

namespace Database\Seeders;

use App\Models\Post;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;

class PostSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        $posts = [
            [
                'name' => 'First Post',
                'description' => 'This is the first post',
                'content' => 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam eget velit nec dolor dictum pellentesque.',
            ],
            [
                'name' => 'Second Post',
                'description' => 'This is the second post',
                'content' => 'Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium.',
            ],
            // Add more posts as needed
        ];

        // Loop through the posts and create records in the database
        foreach ($posts as $post) {
            Post::create($post);
        }
    }
}

Now, we need to call our PostSeeder from the DataBaseSeeder

Navigate to the Database/Seeder/DatabaseSeeder.php, add the below line to the DatabaseSeeder.php file in the run function of it.

$this->call(PostSeeder::class);

Remember to include PostSeeder class, use Database\Seeder\DatabaseSeeder.php:

<?php

namespace Database\Seeders;

use Database\Seeders\PostSeeder;
// use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     */
    public function run(): void
    {
        // Call your seeders here
        $this->call(PostSeeder::class);

    }
}

Finally, Run the below command to start seeding:

php artisan db:seed
image-49.png

Too fast right, now you notice the table get populated with the data:

image-50.png