Laravel run "php artisan optimize" on the server
  • Jordi Llobet
  • 2023 Apr 20

Laravel run "php artisan optimize" on the server

Optimization commands

Laravel 9 contains a set of commands that optimize the operation of the application for better project performance. In this article I will explain how some of these commands work, with special reference to "php artisan optimize". I will discuss where the cache files are stored and in what order they should be executed during deployment.

The optimization files generated by the commands are stored in the bootstrap/cache/ directory.

The "php artisan optimize" command is no longer needed due to recent improvements in the PHP opcode cache. The latest Laravel documentation advises against using this command, although it can still be used in Laravel 9.

"php artisan optimize" creates or overwrites the bootstrap/cache/config.php file. Additionally, this command also creates or overwrites bootstrap/cache/routes-v7.php. This order is a sum of the following 2 orders:

  • "php artisan config:cache" command combines all your configurations into a single file for faster loading. The cache file is saved in bootstrap/cache/config.php. The command clears the previous cache before creating a new one. "php artisan config:clear" undoes the process by removing bootstrap/cache/config.php.
  • "php artisan route:cache" command creates a route cache file for faster route registration. The cache file is saved in bootstrap/cache/routes-v7.php. The command clears the old cache before creating a new one. "php artisan route:clear" clears the cache file.

When we are working in local environment in our Laravel project, if we create a new route we get this error:

To solve this we can run: "php artisan route:cache" which will overwrite and add the new route created in the bootstrap/cache/routes-v7.php file.

On the other hand, we can also run "php artisan optimize" which, as I said before, includes the above command.

Execute these commands on the server

Sometimes we have to provide our project with new functionalities that require the definition of new routes when the project is already in production. We may also find that our hosting service consists of a shared server and we do not have access to your terminal. That is, we can't run the optimization commands we've seen, and therefore can't include the new routes. If we find ourselves in this case, a solution would be to upload the following file every time we run the command related to the routes:

  • bootstrap/cache/routes-v7.php

By default bootstrap/cache folder contains a "gitignore" file. So you can update manually via FTP or simply delete the gitignore file from the folder so that the "git" application can track it.

comillas

If we can't run the Laravel optimization commands on the server because we don't have access to the terminal, we need to update the "bootstrap/cache/" files that were changed when running the commands in local environment.