Migration and Schema Builder in Laravel 7

Laravel provides Migration, and Schema classes for manipulating database tables. It is independent of database type. Migration is useful in version control. For creating a migration, first give command:

  1. php artisian make:migration table_name

It will create a new file in folder database >> migrations with name year_month_day_seconds_table_name.php. For example, above command will create file with name something like 2014_10_12_000000_table_name.php. The default code of this file is:

  1. <?php
  2. use Illuminate\Database\Migrations\Migration;
  3. use Illuminate\Database\Schema\Blueprint;
  4. use Illuminate\Support\Facades\Schema;
  5. class TableName extends Migration {
  6. /**
  7. * Run the migrations.
  8. *
  9. * @return void
  10. */
  11. public function up()
  12. {
  13. //
  14. }
  15. /**
  16. * Reverse the migrations.
  17. *
  18. * @return void
  19. */
  20. public function down()
  21. {
  22. //
  23. }
  24. }

The Blueprint class provides SQL for creating columns in tables. TableName class has two functions, up() and down(). The code for manipulating the table is written in the up() function. The down() function is used to undo the work of up() function. For example, if up() function contains the code for creating a table then down() function will take the code for deleting that table.

Creating and deleting table:

Schema::create() and Schema::drop() are used for creating and deleting table, respectively. In database >> migrations folder, there is a default file named 2014_10_12_000000_create_users_table.php. The code inside this file is:

  1. <?php
  2. use Illuminate\Database\Migrations\Migration;
  3. use Illuminate\Database\Schema\Blueprint;
  4. use Illuminate\Support\Facades\Schema;
  5. class CreateUsersTable extends Migration {
  6. /**
  7. * Run the migrations.
  8. *
  9. * @return void
  10. */
  11. public function up()
  12. {
  13. Schema::create('users', function(Blueprint $table)
  14. {
  15. $table->id();
  16. $table->string('name');
  17. $table->string('email')->unique();
  18. $table->string('password', 60);
  19. $table->rememberToken();
  20. $table->timestamps();
  21. });
  22. }
  23. /**
  24. * Reverse the migrations.
  25. *
  26. * @return void
  27. */
  28. public function down()
  29. {
  30. Schema::drop('users');
  31. }
  32. }

The create() function takes two arguments: table name and operations on the columns of that table (it is a closure). The drop() function takes only table name as argument. In above code, we are creating a table users in up function and deleting this table in down function.

Operations on columns:

Add:

Syntax for adding column is:

  1. <?php
  2. $table->column_type('column_name')->more_operation();

List of all column types is here: Schema Builder in Laravel.

Change:

For changing column use change() function. For example, for changing name column (size 20 to 50) use:

  1. <?php
  2. $table->string('name', 50)->change();

Rename:

For rename use renameColumn() function.

  1. <?php
  2. $table->renameColumn('from', 'to');

Delete:

For deleting a column use dropColumn() function like

  1. <?php
  2. $table->dropColumn('votes');

Adding and dropping Indexes:

For adding indexes use indexes functions like:

  1. <?php
  2. $table->string('email')->unique();

Similarly, for dropping indexes use corresponding functions like

  1. <?php
  2. $table->dropUnique('users_email_unique');

Adding Foreign Key:

For adding a foreign key, first define the column as unsigned type and then add reference (foreign column) and foreign table with it.

  1. <?php
  2. $table->unsignedBigInteger('user_id');
  3. $table->foreign('<span data-pwa-id="pwa-9B9976868EE5B619D6246A30B6906C48" data-pwa-category="" data-pwa-hint="Unknown word: author_id" data-pwa-suggestions="third~authorized~thread~authorised~Thursday" data-pwa-dictionary-word="author_id" class="pwa-mark-done">user_id</span>')
  4. ->references('id')
  5. ->on('users')
  6. ->onDelete('cascade');

Here we are referencing user_id column to id column of users table.

Also see Django vs Laravel vs Ruby on rails

Checking Existence:

For checking existence of a table/ column use Schema::hasTable('table_name') / Schema::hasColumn('table_name', 'column_name').

Dropping Timestamps & SoftDeletes:

For deleting timestamps and soft deletes use functions $table->dropTimestamps(); and $table->dropSoftDeletes(); respectively.

Migration commands:

  1. php artisan migrate: Update database. If you will run this command after configuring database settings then laravel will automatically create/ modify the database tables according to migrations defined in migrations folder. By default laravel will form three tables (users, failed_jobs and migrations). migrations table in database handles the migrations (store migration entries defined in migration folder).
  2. php artisan migrate:rollback: Undo last migration.
  3. php artisan migrate:reset: Undo all migrations. It will delete all tables from database except migrations table.
  4. php artisan migrate:refresh: Undo all migrations and then migrate again.

Further Reading:



ReactJS with Redux Online Training by Edureka

About Harish Kumar

Harish, a fullstack developer at www.lyflink.com with five year experience in full stack web and mobile development, spends most of his time on coding, reading, analysing and curiously following businesses environments. He is a non-graduate alumni from IIT Roorkee, Computer Science and frequently writes on both technical and non-technical topics.

Related Articles

With the expanding market of mobile apps, the developers are struggling to maintain the code bases for Native apps. M...
5 Elite and Imperative Hybrid App Frameworks
Django is a great framework in python. But all of the hosting do not provide django hosting in their shared or free h...
Cheap Django Hosting
Laravel provides blade template. Blade files are similar to php files and cover all features of php files. In additio...
Blade Template in Laravel 7

Complete Python Bootcamp: Go from zero to hero in Python 3

Top Posts

Recent Posts

The Complete Web Developer Course - Build 25 Websites

Meet on Twitter

Subscribe

Subscribe now and get weekly updates directly in your inbox!

Any Course on Udemy in $6 (INR 455)

Development Category (English)300x250

Best Udemy Courses

PHP with Laravel for beginners - Become a Master in Laravel