Creating new table migrations
The joys of database migrations!
Creating new table migrations involves several steps:
- Create a new migration file: Run the following command in your terminal:
php artisan make:migration create_table_name
Replace
create_table_name
with the name of the table you want to create.
This will create a new file in the database/migrations
directory with a timestamped name, e.g., 2023_02_20_140000_create_users_table.php
.
- Write the migration: Open the newly created file and add the necessary code to create the table. For example:
use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint;
class CreateUsersTable extends Migration { /**
- Run the migrations.
- @return void */ public function up() { Schema::create('users', function (Blueprint $table) { $table->id(); $table->string('name'); $table->string('email')->unique(); $table->timestamp('email_verified_at')->nullable(); $table->string('password'); $table->rememberToken(); $table->timestamps(); }); }
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
In this example, we're creating a `users` table with several columns.
3. **Run the migration**: Run the following command in your terminal:
php artisan migrate
This will execute the migration and create the `users` table in your database.
4. **Verify the migration**: Check your database to ensure the table has been created successfully.
Tips:
* Make sure to update the migration file with the correct table name and column definitions.
* Use the `Schema::create()` method to create the table, and `Schema::dropIfExists()` to drop the table in the `down()` method.
* Use the `Blueprint` class to define the table structure.
* Run `php artisan migrate` to execute the migration.
* Verify the migration by checking your database.
That's it! You've successfully created a new table migration.