What are migrations in Laravel, and how are they used?
Jun 20, 2025 am 12:42 AMLaravel migration is a database version control tool that defines and modifies database structure through PHP code to improve collaboration efficiency and environmental consistency. The migration file contains up() and down() methods. The former is used to create or modify database elements, such as tables and fields, and the latter is used to roll back changes. For example, when creating a "users" table, the up() method defines the table structure, and the down() method deletes the table. Laravel provides Artisan command to simplify the migration process: use php artisan make:migration to generate migration files. When creating a model, you can use php artisan make:model User -mf command to execute migration. Use php artisan migrate to rollback. Use php artisan migrate:rollback to reset. Compared with direct operation of the database, migration ensures smooth team collaboration, avoids manual SQL errors, supports cross-environment reuse and provides a convenient rollback mechanism, greatly reducing human errors and repeated labor.
Migrations in Laravel are like version control for your database. They let you define and modify your database structure using PHP code, so you can keep your schema organized, share it with others, and apply changes safely across different environments (like local, staging, production).
This makes it easy to collaborate with other developers and ensures everyone is working with the same database structure — no more guessing what table or column names should be.
What do Laravel migrations look like?
A migration file includes two main methods: up()
and down()
. The up()
method adds or modify database elements (like tables or columns), while down()
rolls those changes back.
For example, if you create a migration to add a "users" table, the up()
method would define how to create that table, and down()
would drop it.
Here's a basic example of what a migration might look like:
public function up() { Schema::create('users', function (Blueprint $table) { $table->id(); $table->string('name'); $table->string('email')->unique(); $table->timestamps(); }); } public function down() { Schema::dropIfExists('users'); }
You don't have to write these manually from scratch — Laravel can generate them for you.
How to create and run migrations
Laravel gives you simple Artisan commands to manage migrations.
To create a new migration file, you can use:
php artisan make:migration create_users_table
Or if you're creating a model along with the migration:
php artisan make:model User -mf
That -mf
flag creates a model, factory, and a migration all at once.
Once your migration is ready, you run it with:
php artisan migrate
This applies all pending migrations. If you want to roll back the last batch of migrations (for example, if something went wrong), you can use:
php artisan migrate:rollback
And if you really want to start over:
php artisan migrate:fresh
This drops all tables and re-runs all migrations from scratch.
Why using migrations is better than editing the DB directly
- Collaboration : Everyone on the team can stay in sync without manually updating each other's databases.
- Consistency : You avoid mistakes that come from writing raw SQL by hand.
- Reusability : Migrations can be reused across different environments.
- Rollbacks : You can undo changes easily if something breaks.
Without migrations, you'd have to remember every change you made to the database and manually reapply them somewhere else — which is error-prone and time-consuming.
So yeah, migrations are basically a safe, repeatable way to manage your database structure in Laravel. Once you get used to them, you'll probably never want to go back to writing raw SQL again.
The above is the detailed content of What are migrations in Laravel, and how are they used?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Single-page applications (SPAs) can be built using Laravel and Vue.js. 1) Define API routing and controller in Laravel to process data logic. 2) Create a componentized front-end in Vue.js to realize user interface and data interaction. 3) Configure CORS and use axios for data interaction. 4) Use VueRouter to implement routing management and improve user experience.

Efficient methods for testing Laravel API interfaces include: 1) using Laravel's own testing framework and third-party tools such as Postman or Insomnia; 2) writing unit tests, functional tests and integration tests; 3) emulating a real request environment and managing database status. Through these steps, the stability and functional integrity of the API can be ensured.

Custom Laravel user authentication logic can be implemented through the following steps: 1. Add additional verification conditions when logging in, such as mailbox verification. 2. Create a custom Guard class and expand the authentication process. Custom authentication logic requires a deep understanding of Laravel's authentication system and pay attention to security, performance and maintenance.

The steps to create a package in Laravel include: 1) Understanding the advantages of packages, such as modularity and reuse; 2) following Laravel naming and structural specifications; 3) creating a service provider using artisan command; 4) publishing configuration files correctly; 5) managing version control and publishing to Packagist; 6) performing rigorous testing; 7) writing detailed documentation; 8) ensuring compatibility with different Laravel versions.

Integrating social media login in the Laravel framework can be achieved by using the LaravelSocialite package. 1. Install the Socialite package: use composerrequirelaravel/socialite. 2. Configure the service provider and alias: add relevant configuration in config/app.php. 3. Set API credentials: Configure social media API credentials in .env and config/services.php. 4. Write controller method: Add redirection and callback methods to handle social media login process. 5. Handle FAQs: Ensure user uniqueness, data synchronization, security and error handling. 6. Optimization practice:

Implementing password reset function in Laravel requires the following steps: 1. Configure the email service and set relevant parameters in the .env file; 2. Define password reset routes in routes/web.php; 3. Customize email templates; 4. Pay attention to email sending problems and the validity period of tokens, and adjust the configuration if necessary; 5. Consider security to prevent brute-force attacks; 6. After the password reset is successful, force the user to log out of other devices.

Common security threats in Laravel applications include SQL injection, cross-site scripting attacks (XSS), cross-site request forgery (CSRF), and file upload vulnerabilities. Protection measures include: 1. Use EloquentORM and QueryBuilder for parameterized queries to avoid SQL injection. 2. Verify and filter user input to ensure the security of output and prevent XSS attacks. 3. Set CSRF tokens in forms and AJAX requests to protect the application from CSRF attacks. 4. Strictly verify and process file uploads to ensure file security. 5. Regular code audits and security tests are carried out to discover and fix potential security vulnerabilities.

Middleware is a filtering mechanism in Laravel that is used to intercept and process HTTP requests. Use steps: 1. Create middleware: Use the command "phpartisanmake:middlewareCheckRole". 2. Define processing logic: Write specific logic in the generated file. 3. Register middleware: Add middleware in Kernel.php. 4. Use middleware: Apply middleware in routing definition.
