Schema builder helps you create and change database tables easily using code. It saves time and avoids manual work.
0
0
Schema builder (columns, types) in Laravel
Introduction
When you want to create a new database table for your app.
When you need to add or change columns in an existing table.
When you want to define the type of data each column holds.
When you want to keep your database structure consistent across different environments.
When you want to share database changes with your team using code.
Syntax
Laravel
Schema::create('table_name', function (Blueprint $table) { $table->type('column_name'); });
Use Schema::create to make a new table.
Inside the function, use $table->type('column_name') to add columns with specific data types.
Examples
This creates a
users table with an auto-increment ID, a name column as text, an age column as number, and timestamp columns for created and updated times.Laravel
Schema::create('users', function (Blueprint $table) { $table->id(); $table->string('name'); $table->integer('age'); $table->timestamps(); });
This adds a nullable text column
content and a boolean published column with default false to the existing posts table.Laravel
Schema::table('posts', function (Blueprint $table) { $table->text('content')->nullable(); $table->boolean('published')->default(false); });
Adds a decimal column named
price with 8 digits total and 2 digits after the decimal point.Laravel
$table->decimal('price', 8, 2);
Sample Program
This migration creates a products table with columns for ID, name, optional description, price with decimals, a boolean for stock status, and timestamps.
Laravel
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateProductsTable extends Migration { public function up() { Schema::create('products', function (Blueprint $table) { $table->id(); $table->string('name'); $table->text('description')->nullable(); $table->decimal('price', 8, 2); $table->boolean('in_stock')->default(true); $table->timestamps(); }); } public function down() { Schema::dropIfExists('products'); } }
OutputSuccess
Important Notes
Always run migrations using php artisan migrate to apply schema changes.
Use nullable() to allow empty values in a column.
Use default() to set a default value for a column.
Summary
Schema builder lets you create and modify database tables using simple code.
You define columns and their data types inside a function with $table.
This approach keeps your database structure organized and easy to share.