View the SQL using php artisan migrate --pretend in Laravel

When you want to run migrations, we have a very useful option: the --pretend command. This command allows us to obtain the SQL that Laravel would execute internally in the database. That is, it doesn't directly apply the changes, but rather shows you the SQL statements that will be executed.

In my case, for example, as you can see on the screen, many migrations appear. This is because I have poor synchronization between the migrations and the database, but oh well... that's another story.

$ php artisan migrate --pretend

As you can see, Laravel spits out all the SQL to us through the console. The only caveat is:

  1. Some lines have strange characters (strange icons).
  2. It doesn't add semicolons at the end of each sentence.

So, you need to format it a little to make it more readable. If you want, you can ask ChatGPT to format it for you. But beyond that, the most important thing is that you now have the SQL ready to execute in your database.

What is this for?

You might be wondering: what could this be useful for?

As I've discussed in other videos, this is especially valuable when you're working in shared environments, such as staging or production servers.

In these environments:

  1. You don't always have access to the terminal.
  2. Therefore, you can't run php artisan migrate directly.
  3. However, you can access the database manager (e.g., phpMyAdmin or DBeaver).

So, if you need to create new tables or apply changes, you can copy this SQL and run it directly.

Before I knew about this option, what I did was:

  1. Go to the database state manager.
  2. Export the newly created table.
  3. Retrieve the resulting SQL.
  4. Then run it in production.

A more cumbersome process, especially if you had to modify existing tables.

With --pretend, everything is easier

Now, with this --pretend option, everything is simplified:

  1. You can directly view the SQL, even if the migration modifies existing columns or adds constraints.
  2. You no longer rely on exporting from the visual manager.
  3. And you can easily copy and paste the SQL to run it in other environments.

I agree to receive announcements of interest about this Blog.

We will see a wildcard to see the SQL of the migrations in Laravel.

- Andrés Cruz

En español