logo
podcast Podcast
get help Get Unstuck

How would you override a URL in a command?

And why would you even want to?

Joel Clermont
Joel Clermont
2024-09-27

I've already talked about the command Aaron built to generate an ebook from these daily tips.

I have one more story to share about this command though.

We generate these books running the command locally, but I want the generated book to have links to the masteringlaravel.io domain.

It won't do a reader much good if everything links to masteringlaravel.local, which we use for local development.

So this is the problem I was trying to solve: How could I have my command use a different URL than is present in the .env for building routes?

One option was to just prepend my command in the terminal:

APP_URL=masteringlaravel.io php artisan tips:generate-book

This does work, but it requires me to remember to prepend the command, and not just run the command on autopilot. I wanted a better solution.

I discovered I couldn't just override config values inside the command. Routes were already bound and the UrlGenerator was already built by the point by command was invoked.

But digging around the UrlGenerator, I found a method that looked promising:

URL::formatHostUsing(fn() => 'https://masteringlaravel.io');

This did change the host in all links generated from routes, but it did not affect Vite assets. So I kept digging and found an even better solution:

URL::forceRootUrl('https://masteringlaravel.io');

This approach worked for both links and Vite assets. Success!

I'll admit up that this tip has a very limited audience, but even if it only helps a few people, I still think it's good to dig a little deeper in the framework and see how things work.

Tuck away this little bit of knowledge in case you need it later. And it will also be there for me in the future if I forget and search the web for an answer!

Here to help,

Joel

P.S. Collect all the tips in book form: 2023 Volume 1, 2024 Volume 1, and 2024 Volume 2.

Toss a coin in the jar if you found this helpful.
Want a tip like this in your inbox every weekday? Sign up below 👇🏼
email
No spam. Only real-world advice you can use.