In Laravel, one straightforward method to include public CSS and JavaScript files is by using the asset() helper function. This approach is ideal for small to medium-sized projects due to its simplicity and clarity.
Start by creating a common folder inside the public directory. Place your frequently used CSS and JS files in this folder, such as style.css and script.js.
Next, use the asset() helper within your Blade templates to generate URLs for these assets:
<link rel="stylesheet" href="{{ asset('common/style.css') }}">
<script src="{{ asset('common/script.js') }}"></script>
This ensures your asset paths are correctly resolved regardless of URL configurations or deployment environments.
Laravel also provides a more flexible and scalable way to handle assets by using a custom asset management approach. This is more suitable for larger applications with modular resource handling needs.
Inside the resources/assets directory, create a common folder and add your style.css and script.js files there.
Now open config/app.php and add an alias in the aliases array to reference a custom class for loading assets:
'aliases' => [
'Common' => App\Library\Common::class,
],
This sets up a convenient alias called Common for referencing resources in your views.
After setting up the alias, use the custom @common() directive to load assets in your Blade templates:
<link rel="stylesheet" href="@common('style.css')">
<script src="@common('script.js')"></script>
This method automatically resolves asset paths and simplifies tag generation for your views.
This article covered two approaches for including public assets in a Laravel project:
Depending on your project’s size and structure, you can choose the approach that best fits your development workflow and improves front-end resource management.