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
- Open your command line interface.
- Run the following command to create a new migration file with a descriptive name:
bash
php artisan make:migration createuserstable
- This command will generate a new migration file in the
database/migrations
directory.
- This command will generate a new migration file in the
Step 2: Defining the Schema
- Open the newly created migration file (e.g.,
2024_01_26_093217_create_users_table.php
). - Inside the
up
method, define the schema for theusers
table using theSchema
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
- To run the migration and apply the schema to the database, execute the following command in the command line:
bash php artisan migrate
- This will create the
users
table in the database with the defined fields.
- This will create the
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)