Support Laravel Version: Laravel 8, Laravel 9, Laravel 10, Laravel 11 With Latest All Version Support.
In Laravel migrations are used to create database tables. These migrations are version-controlled and allow you to define the structure of your database tables in a PHP file, making it easy to share and manage changes across different environments. Here’s how you can create tables in Laravel migrations:
1. Create a Migration:
Use the artisan command to create a new migration file. This command will generate a new PHP file in the `database/migrations` directory.
php artisan make:migration create_table_name
Replace `table_name` with the name you want to give your table.
2. Edit the Migration File:
Open the generated migration file in the `database/migrations` directory. You’ll see two methods: `up()` and `down()`. In the `up()` method, define the schema for creating the table using the `Schema` facade.
use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateTableNameTable 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'); } }
Replace `’column_name’` with the actual column names you want to define in your table. You can use various column types such as `string`, `integer`, `text`, `boolean`, `date`, etc. Refer to the Laravel documentation for a full list of available column types and options.
3. Run Migrations:
Once you’ve defined your migration, run the migration using the artisan command:
php artisan migrate
This command will execute all pending migrations and create the corresponding tables in your database.
4. Rollback Migrations (Optional):
If you need to rollback your migration (i.e., undo the changes), you can use the `migrate:rollback` command:
php artisan migrate:rollback
This will rollback the last batch of migrations.
That’s it! You’ve now created a table using Laravel migrations. Repeat the process for any additional tables you need to create, and remember to always keep your migrations in sync with your database schema.