DEV Community

Sunday Moses
Sunday Moses

Posted on

Creating and Migrating a Schema in Laravel

In this tutorial, we'll walk through the process of creating a schema with four fields (id, name, address, timestamp) and migrating it to be used in the database using Laravel's migration feature.

Step 1: Creating a Migration

  1. Open your command line interface.
  2. Run the following command to create a new migration file with a descriptive name: bash php artisan make:migration createuserstable
    1. This command will generate a new migration file in the database/migrations directory.

Step 2: Defining the Schema

  1. Open the newly created migration file (e.g., 2024_01_26_093217_create_users_table.php).
  2. Inside the up method, define the schema for the users table using the Schema facade. Add the required fields and their data types:

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

public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->text('address')->nullable();
$table->timestamp('createdat')->useCurrent();
$table->timestamp('updatedat')->default(DB::raw('CURRENTTIMESTAMP ON UPDATE CURRENTTIMESTAMP'));
});
}`

Step 3: Running the Migration

  1. To run the migration and apply the schema to the database, execute the following command in the command line: bash php artisan migrate
    1. This will create the users table in the database with the defined fields.

Congrats! You've successfully created a schema for a users table with four fields and migrated it using Laravel. It's now ready to be utilized in your database operations!

Top comments (0)