To create and migrate a database table in Laravel, you can follow these steps:
Step 1: Generate a new migration file using the make:migration
Artisan command. This command will create a new migration file in the database/migrations
directory.
php artisan make:migration create_table_name
Step 2: Open the newly created migration file and define the structure of your database table using the up
method. You can use the Schema
facade to create the table and define its columns.
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateTable extends Migration
{
public function up()
{
Schema::create('table_name', function (Blueprint $table) {
$table->id();
$table->string('column_name');
// Add more columns as needed...
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('table_name');
}
}
Step 3: Run the migration using the migrate
Artisan command. This command will create the table in the database specified in your .env
file.
php artisan migrate
And that's it! You have now created and migrated a database table in Laravel.