Laravel
Beginner
1 min read
Altering Tables and Running Migrations
Example
<?php
// database/migrations/2024_06_01_000001_add_views_to_posts_table.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::table('posts', function (Blueprint $table) {
// Add new columns
$table->unsignedBigInteger('view_count')->default(0)->after('status');
$table->string('featured_image')->nullable()->after('body');
// Modify an existing column (requires nullable change)
$table->string('slug', 300)->change();
// Add a new index
$table->index('view_count');
});
}
public function down(): void
{
Schema::table('posts', function (Blueprint $table) {
$table->dropIndex(['view_count']);
$table->dropColumn(['view_count', 'featured_image']);
});
}
};
// Terminal commands:
// php artisan migrate — run pending migrations
// php artisan migrate:rollback — roll back the last batch
// php artisan migrate:rollback --step=3
// php artisan migrate:fresh --seed — drop all + migrate + seed
// php artisan migrate:status — show migration status
Related Resources
Laravel Reference
Complete tag & property list
Laravel How-To Guides
Step-by-step practical guides
Laravel Exercises
Practice what you've learned
More in Laravel