Laravel Command php artisan optimize

Created At: 2023-02-03 20:27:10 Updated At: 2023-11-03 08:47:33

This has been a few times, that php artisan optimize made my life hell during app developement. Long story short, it might lead to 404 error. It took me around 30 minutes to figure out what was going on. 

Tried to test this on Postman. I got 404, test on browser 404, test on the Flutter app, still got 404.

404 error means route not found which leads to page not found. If you ever use php artisan optimize and then add or change a new route, you will get 404 error. Of course there are other reasons why this could happen.

Benefits 

The primary purpose of php artisan optimize is to help you make your app response faster, which means reducing number of files to looked for each http request.

Each time you make a http request, Laravel looks for a lot of files, which may slow down the response of the app. That's why we use php artisan optimize.

Downside

But the downside is that, if you make changes in your routes name or add new routes, you will see that you get 404.

That happens because php artisan optimize compiles files and put them in a speical folder called bootstrap/cache/compiled.php

So your newly included files and routes are not reflected in that directory. After making changes to your routes you need to run 

  1. php artisan cache:clear
  2. php artisan config:clear

Or you may also do php artisan optimize:clear but it's scary since it will remove all the cache files. You must be careful when you use this in production. See the below picture with above command

See how it removes all the cache from the system.

So the rule of thumb in development phase don't run php artisan optimize. But in production after your app hosted then you may run php artisan optimize.

Comment

Add Reviews