Tuesday 18 June 2024

Setting up Migrations for a Laravel 11 API Model

Migrations in Laravel are a way to change the schema of a database in an organized and version-controlled manner. They provide a way to easily share the schema of the database and make modifications to it. Migrations are like creating a schema once and then sharing it many times.

Pre-requisites

We'll assume that the model was created using the approach in this blog post.

When the model was created in the pre-requisite, a migration file was also created for our model in the directory database/migrations.

It is in this file that we set the field types which will be populated as records are used within CRUD operations and listings. Below are examples of how these should be set in order to facilitate this:

public function up(): void

{

Schema::create('yourmodel', function (Blueprint $table) {

    $table->id();

    $table->string('name');

    $table->text('description')->nullable();

    $table->timestamps();

});

}

public function down(): void

{

Schema::dropIfExists('yourmodel');

}

It would be possible to run the migrations as is though:

php artisan migrate

but we may be best served, by seeding these migrations as we run them in order to have some test data.

 

No comments:

Post a Comment