PHP

Include js and css file in laravel using blade

Sometimes it is required to add js, css and image file in global that can be used by all other view files. Laravel provides a hand on procedure to include js, css and image in header links and script tags. So in this tutorial we are going to include js and css file in laravel using blade.

Include js and css file in laravel
Include js and css file in laravel

Include js and css file in laravel using blade

A simple and easy way to use the Blade templating engine to get a fully ready layout system. We will create a few site pages (home, about, projects, contact). Here is a table of the pages that we will use and the layouts that they will use.

1. Routing

It is necessary to set router for pages to work inside views

Since we are going to render view files and include js, css and images to it there is no need to write any messy code for controller. We are just simply going to write some view files inside view folder.

If you want more information on that, check out our Laravel tutorials session.

Now that we have our routes setup, we will start our work with the home page. Open up app/views/pages/home.blade.php. Inside of that file, we will pull together a layout file, a page file, and includes. In this way we don’t need to repeat to include same assets again and again in each view files.

2. Views

Before you start with views make sure you follow this file structure

3. Includes

We are now going to add head, header and footer head.blade.php

header.blade.php

footer.blade.php

4. Default layouts and pages

With our includes ready, let’s make our first layout. We will be using @include to bring in slices and @yield to bring in content from the individual pages we will be using. (Include js and css file in laravel).

5. Home and contact page

We won’t dive too far into the actual content of each page. The home page and contact pages will use the same layouts/default.blade.php. We won’t have to reuse the code in the layout or the includes now!

Blade lets us use the layout that we just created by using@extends. By creating @section, we create a section that will be used in the layout. Here we use @section('content')and in our layout, all that we type here will be injected in@yield in the layout.

pages/home.blade.php

pages/contact.blade.php

Conclusion

Using blade technique we can add a js, css and a constant layout that is included through out the website. To disable the layout we simple need to call  $this->layout = null and done. Thank you for reading & please subscribe to get more updates.

Share

Leave a Comment

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