Add new column to existing table in Laravel

Do you want to add new column in existing database table with laravel ? It’s simple. We can do it easily by creating a new migration structure. At first, we will figure out following three things before creating a new migration structure.

  1. Name
  2. Type
  3. Position

At first we have to figure out name of the column we want to add. We can set any name.Type refers to nature of the data we will store later. It may be string, integer, floating point, character or any other. Finally, position is the location where we will add our column.

For example, we want to add address to users table. Name will be address, Type will be string and let add address after email in users table.

How to make specific table migration in laravel ?

Now, we have to create migration structure for this. An artisan command will do it for us.

You can see laravel official documentation for details about creating migrations with artisan commands.

We will see new migration file inside database/migrations/ directory like this:

As we know, up method will be executed when we migrate and down method will be executed when we rollback the migrations. We have add both logic for adding new column address to users table.

Our migration should look like

Here, an address will be added just after the email in users table when we run the migrate command. On the other way, when we rollback, address will be removed from the users table. This is what we want.

Now, run the migrate command from the terminal.

After this, we will see address column in users table in database.

Conclusion

There are few things we need to consider i.e. name, type and location . After that a new migration structure with few lines of code will do it for us. In this way, we can add new column to existing table in database.


sagautam5

sagautam5

Computer Enginner, A Laravel Developer,
http://sagargautam.stacklearning.com

Leave a Reply

Your email address will not be published. Required fields are marked *