What is the difference between the asset helpers?

And which one should you use?

Joel Clermont
Joel Clermont
2024-04-15

On our friendly Laravel Slack community, someone recently asked about the difference between using the asset() helper and the mix() helper. And now, new Laravel apps use Vite by default, so let's add Vite::asset() to the discussion as well.

asset() is the most basic. It just takes a path and builds out a full URL. Most times it's something you're serving locally out of your public directory, but it could also be coming from a CDN domain if you've configured it that way.

mix() and Vite::asset() go a step further. Because these tools bundle your assets, there is often a special path needed to resolve an asset. For example, the file name may include a hash to aid in cache busting. Or a file may live within a larger bundle.

Both of these tools generate a manifest file which provides the mapping from an asset name to one of these generated path names. So the helpers resolve the correct name from the manifest and output the resolved URL.

During development mode, those helpers have an extra check for "hot" mode to bypass that manifest process, since you aren't generating a manifest when doing active development.

So, which one should you use? The short answer is that if you're using Mix or Vite, you should use their included helper for resolving assets. If you bypass these tools and use the simpler asset() helper directly, you may either get missing file errors or bypass cache busting.

That being said, there is one big exception, which is if you're using Vapor. Check the Vapor docs on asset bundling for the current recommendations if you're deploying to Vapor.

Hope that helps,

Joel

P.S. If you'd like to learn more about the Mastering Laravel Slack community, check out our page, and feel free to reply with any questions. It's a great way to level up your skills.

Toss a coin in the jar if you found this helpful.
Want a tip like this in your inbox every weekday? Sign up below 👇🏼

Level up your Laravel skills!

Each 2-minute email has real-world advice you can use.