How to Load different CSS and JS for different views in Laravel

Load different css/js for different views in laravel

In many applications when we start the project we tried to keep the common things separate, for example in PHP when we developed the website we keep the header, sidebar, footer separate, and JS and CSS we also make separate files. This approach helps us to manage the changes easily in the project.

The same way we separate the parts in Laravel blade templates. We keep the master layout and inherit its part in the child layout in different views.

We keep CSS and JS in the header and footer in the master template. But what if we need different CSS and JS file in child templates. Well, we can do this using include file method, but in this way, we have to make multiple files to include in different views if required different JS and CSS for different views. So what is the solution?

Laravel provides a simple and easy way to load different CSS and JS for different views in Laravel using Blade Stacks.

It’s really simple, put the below code in your master layout in view.

<head>
    @stack('css')
</head>

Now at the bottom of your layout before the </body> tag place the following.

 @stack('scripts')
</body>

Now you can use the following code in child layout to include different CSS and JS in different views. The child layout will access the master layout CSS and JS with its own defined CSS and JS.

@push('scripts')
    <script src="js/custom.js"></script>
@endpush

@push('css')
     <link rel="stylesheet" href="css/custom.css">
@endpush

Conclusion:

You can see how easy is to push new and separated CSS and JS file in each and every view in the Laravel. You do not need to load one by one JS and CSS for each and every file.

@push provides us a very helping hand in the Laravel to include the files. It is helpful in a situation like when we have made some modifications in some of the websites and we only want to share those CSS changes with some of the old pages. So you can achieve that by simply using @push method which we have explained above briefly.

You can also check How to block IP addresses from accessing the application

Hope you liked it. If you have any queries and suggestion regarding this article please comment us below and let us know you points.

Spread the love

Leave a Reply

Your email address will not be published. Required fields are marked *