Migrate “pretend” – view actual SQL queries before you run them

Laravel has convenient database migrations mechanism, which allows us to track database changes and easily roll them back if needed. But what is hiding behind the scenes? What if we need to know actual SQL queries that have been generated during the migration? Or another scenario – what if we want to check the SQLs before they are actually run? There’s a trick for both of it.

Artisan command migrate comes with a neat option –pretend. All it does is generating SQLs and showing them for you in Terminal or Command line.

Let’s take a look at simple migration example:

class CreateTestTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
        Schema::create('tests', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->timestamps();
        });
	}

And now we run it with command php artisan migrate –pretend.
Here’s the result:

0202_laraveldaily_pretend_01

Not really pretty, but you can see the SQL statement here.
And let’s take it a step further and add another migration, really similar:

class CreateTest2Table extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
        Schema::create('tests2', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title2');
            $table->timestamps();
        });
	}

Same command – here’s the result, it shows both commands one after another:

0202_laraveldaily_pretend_02

Simple, but useful trick. Do you know some more tricks with migrations? Let me know in the comments!

Like our articles?
Check out our Laravel online courses!

4 COMMENTS

  1. You can do

    Event::listen(“illuminate.query”,function($query){

    echo “<pre>”;
    print_r($query);
    echo “</pre>”;

    });

    And put that inside of your app somewhere 🙂 It listens for when a DB query is about to get executed and then, you just take that query and echo it out in some <pre> tags.

  2. Thanks Povilas, great tip. I wanted to add recursion to an existing table and found out how to set up the migration in Laravel… but wanted to translate these 2 “adjustments” to SQL to I could modify the (already) migrated table. So I created a test migration, added the code, ran the “pretend” migration and scooped up the generated SQL. After deleting the temp migration I just ran the 2 “alter table” commands and voila! It worked like a charm!

    And great comment Surtep, I use this often but never thought to apply it to artisan commands.

LEAVE A REPLY

Please enter your comment!
Please enter your name here