How to include css and js in Laravel 5



It’s a basic need to include external or internal css and js in our application. Today in this tutorial we’ll discuss how to include css and js in Laravel 5 application. Before laravel 5 we are using HtmlBuilder to add style and scripts. But in laravel 5 HtmlBuilder has been removed, so HTML::style() is no longer available now. After including HtmlBuilder package you can easily add your css and js in laravel 5 application. There are many ways to include css and js in laravel 5. Here we are showing two methods HtmlBuilder and URL::asset() to include css and js in Laravel 5.

1. Using URL Class :- This class is inbuilt in laravel 5. so you can easily add your css and js using it in your view files.

To include internal css and js:

<link rel="stylesheet" href="{{ URL::asset('css/bootstrap.css') }}">
<script type="text/javascript" src="{{ URL::asset('js/jquery.min.js') }}"></script>

Note:- Default path will be your application root. so css and js directory would be located on your application root.

To include external css and js:

<link rel="stylesheet" href="{{ URL::asset('//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css') }}">
<script type="text/javascript" src="{{ URL::asset('//code.jquery.com/jquery-3.2.1.min.js') }}"></script>

2. Using HtmlBuilder –  HtmlBuilder has been removed in laravel 5. So now you can include laravelcollective html toyour laravel 5 application to use HtmlBuilder. Run following line from terminal.

composer require "laravelcollective/html":"^5.2.0"

Next, add your new service provider to the providers array of config/app.php

'providers' => [
    // ...
    Collective\Html\HtmlServiceProvider::class,
    // ...
  ],

Finally, add two class aliases to the aliases array of config/app.php:

'aliases' => [
    // ...
      'Form' => Collective\Html\FormFacade::class,
      'Html' => Collective\Html\HtmlFacade::class,
    // ...
  ],

After include html package you can use HTML class methods to add script and style to your application.

To include internal css and js

{!!Html::style('css/style.css')!!}
{!!Html::script('js/script.js')!!}

To include external css and js

{!!Html::style('//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css')!!}
{!!Html::script('//code.jquery.com/jquery-3.2.1.min.js')!!}

Using both methods you can easily add your css and js to laravel application. These methods make html style and script tags auto, so no need to write lines of code for these tags.