How to Create And Apply Migrations In Laravel?

8 minutes read

Creating and applying migrations in Laravel is a crucial step in database management. Migrations allow you to modify and maintain the database schema over time, making it easier to collaborate with other developers and keep track of changes. Here's how you can create and apply migrations in Laravel:


To create a migration, you can use the make:migration Artisan command. Open your command line interface and navigate to your Laravel project directory. Then, run the following command:

1
php artisan make:migration create_table_name


Replace table_name with the desired name for your table. This command will create a new migration file in the database/migrations directory.


Open the newly created migration file, and you'll find two methods: up() and down().


The up() method is used for defining the changes that need to be made to the database schema. You can use Laravel's schema builder to create tables, add columns, define indexes, and more within this method.


For example, to create a users table with id, name, and email columns, you can write the following code within the up() method:

1
2
3
4
5
6
7
8
9
public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->string('email')->unique();
        $table->timestamps();
    });
}


The down() method, on the other hand, should be used to reverse the changes made in the up() method. This is helpful when you need to rollback your changes later on. So, if you need to drop the users table in case of a rollback, you can add the following code within the down() method:

1
2
3
4
public function down()
{
    Schema::dropIfExists('users');
}


Once you've defined your migration, you can apply it to the database by running the migrate Artisan command:

1
php artisan migrate


This command will execute the up() method of all pending migrations in chronological order. Laravel's migration system keeps track of the migrated files to ensure that they're run only once.


In summary, creating and applying migrations in Laravel involves using the make:migration command to generate a migration file, writing the schema modifications within the up() method, defining rollback actions in the down() method, and finally applying the migrations to the database using the migrate command.

Best Laravel Frameworks Books to Read in 2024

1
Laravel: Up and Running: A Framework for Building Modern PHP Apps

Rating is 5 out of 5

Laravel: Up and Running: A Framework for Building Modern PHP Apps

2
Beginning Laravel: Build Websites with Laravel 5.8

Rating is 4.9 out of 5

Beginning Laravel: Build Websites with Laravel 5.8

3
Laravel: Up & Running: A Framework for Building Modern PHP Apps

Rating is 4.8 out of 5

Laravel: Up & Running: A Framework for Building Modern PHP Apps

4
Laravel: Up & Running

Rating is 4.7 out of 5

Laravel: Up & Running

5
Practical Laravel: Develop clean MVC web applications

Rating is 4.6 out of 5

Practical Laravel: Develop clean MVC web applications

6
Laravel - Un framework efficace pour développer vos applications PHP

Rating is 4.5 out of 5

Laravel - Un framework efficace pour développer vos applications PHP


What is the purpose of Laravel's "onDelete" method in a migration?

The purpose of Laravel's "onDelete" method in a migration is to specify the action that should be taken when a foreign key constraint is violated during a deletion operation.


When defining a foreign key constraint in a migration, you can use the "onDelete" method to specify the desired action. The available options are:

  1. "cascade": When a record in the parent table is deleted, all associated records in the child table will also be deleted.
  2. "restrict": Prevents deletion of a record in the parent table if there are associated records in the child table.
  3. "set null": Sets the foreign key field in the child table to null when the associated record in the parent table is deleted.
  4. "no action": Does nothing when a foreign key constraint is violated during deletion. It cancels the deletion operation and raises an error.


By selecting the appropriate "onDelete" action, you can define the behavior of your database tables when records are deleted, maintaining data integrity and preventing any unexpected errors or inconsistencies.


How to rename a column in Laravel using migrations?

To rename a column in Laravel using migrations, you can follow these steps:

  1. Open your terminal and navigate to your Laravel project directory.
  2. Generate a migration using the make:migration Artisan command. For example, to rename the old_column_name to new_column_name in the your_table_name table, run the following command: php artisan make:migration rename_column_in_your_table_name --table=your_table_name
  3. This will create a new migration file in the database/migrations directory with a timestamp in its file name. Open the generated migration file.
  4. In the up method of the migration file, use the Schema::table method with the renameColumn method to rename the column. For example: use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class RenameColumnInYourTableName extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('your_table_name', function (Blueprint $table) { $table->renameColumn('old_column_name', 'new_column_name'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('your_table_name', function (Blueprint $table) { $table->renameColumn('new_column_name', 'old_column_name'); }); } }
  5. Save the migration file.
  6. Finally, run the migrations using the migrate Artisan command: php artisan migrate This will execute the migration and rename the specified column in the database table.


How to add a default value to a column in Laravel migration?

To add a default value to a column in a Laravel migration, you can use the default method provided by the Laravel Schema Builder. Here's an example of how to do this:

  1. Open the migration file you want to modify. It is usually located in the database/migrations directory.
  2. Inside the up method, find the table method and locate the column you want to add a default value to.
  3. Add the default method to the column definition and set the desired default value as an argument. For example, if you want to set the default value of a name column to "John Doe", you can use the following code:
1
$table->string('name')->default('John Doe');


  1. Save the migration file.
  2. Run the migration command to apply the changes to your database:
1
php artisan migrate


After running the migration, any new rows inserted into the table will have the default value set for the specified column. Note that this will not affect existing rows in the database.

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

Related Posts:

Creating and applying migrations in CakePHP is an essential part of managing database schema changes and version control. Migrations allow you to define database changes and easily apply or rollback those changes as needed. Here is an overview of how to create...
API authentication is an essential aspect of securing your Laravel application. Laravel provides various built-in mechanisms to implement API authentication effortlessly. One widely used method is to leverage Laravel Passport, a full OAuth2 server implementati...
To create a new Laravel project, you can follow these steps:Open your command-line interface (CLI) or terminal.Navigate to the directory where you want to create the Laravel project.Run the following command: composer create-project --prefer-dist laravel/larav...