Laravel is one of the best PHP frameworks. Laravel provides a lot of features such as authentication, Migration, Eloquent, Blade and so on. We all have been using migration which is a very easy and handy feature that helps to create tables in one command.
Laravel hides the complexity for us and does all the magic behind the scene. This goes for migrations too. When we run php artisan migrate
, all of our migration files are converted into SQL queries and then executed. In this article, we are going to view the actual SQL queries before actual tables are created.
The artisan command has a option for -pretend
. This will allow us to view the SQL queries in the terminal. We can also seed our database using tinker
which has been explained in the article “How to use Tinker in Laravel Application“.
Let’s test in our project.
We will create a new migration file for articles
table and run the migration. First of all, we create our migration with command:
php artisan make:migration createArticlesTable --create=articles
This will create a migration file under database/migrations
directory. Open this migration file and make some changes so that our final migration file looks like below:
// database/migrations/createArticlesTable.php public function up() { Schema::create('articles', function (Blueprint $table) { $table->increments('id'); $table->string('title'); $table->string('slug'); $table->integer('author_id'); $table->text('body'); $table->timestamps(); }); }
Now, its time to run the migration. To view the actual SQL queries, we need to pass -pretend
option along with migrate command. So, run the artisan command below:
php artisan migrate -pretend
This will give us SQL queries in the command line as like below:
Mostly, we have multiple migration files. So, let’s try that. Create another migration file for comments
table. Run the migration
php artisan make:migration createCommentsTable --create=comments
Let’s change our migration file adding some columns in the table.
public function up() { Schema::create('comments', function (Blueprint $table) { $table->increments('id'); $table->integer('article_id'); $table->integer('author_id'); $table->timestamps(); }); }
Now, lets migrate our two migration file with the same command php artisan migrate --pretend
Then, we will see the actual SQL query as in below screenshot.
Conclusion
In this way, we can view the actual queries that are executed in the backend besides our view. This is all about viewing actual SQL queries before migration. This is not always preferred but we may need to view the SQL queries sometimes. Thus, this will help. If you have got any questions, please leave a comment below.