1 year ago

Laravel: Dynamically add and remove CSS or Script

Posted 1 year ago by kundefine

It is really easy to include all the common CSS or Script in the page. But the problem arise when you don't need some CSS or Script in the page. If you checkout my below code you will find out what i am trying to say.

I already instantiate my CSS class in header.blade.php and its included in the master.blade.php. After that index.blade.php extends master.blade.php

But the problem is When index.blade.php render it's create a new instance of the CSS class. header instance is gone.

I am trying to use my CSS Class

=> as service provider

=> share as view variable

=> as a Facade

  1. CSS.php (myclass for add or remove css)
namespace App\AppGlobal;

class CSS {
    public $css = []; // all my css filename and path is store in here

    // add css
    public function add($path, $filename) {
        $path = asset($path);
        $this->css[$filename] = $path;

        return $this->css;

    // remove css
    public function remove($filename) {
        if(array_key_exists($filename, $this->css)) {

    // print css
    public function print() {
        $output = '';
        if(count($this->css)) {
            foreach($this->css as $filename => $path) {
                $output .= "<link rel='stylesheet' href='{$path}/{$filename}'>\n";
        echo $output;

  1. master.blade.php (look like below)
{{-- include tha header --}}

{{-- the main content section --}}

{{-- include tha footer --}}
  1. header.blade.php (look like below)
<!doctype html>
<html lang="en">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>{{config('app.name', 'ColorSpray')}}</title>

    {{-- add all common css --}}
    <?php $css->add('some/path', 'filename.css') ?>
    {{-- add additional css--}}
    {{-- remove exitsing css--}}
    {{-- print all my css --}}
    <?php $css->print(); ?>
  1. index.blade.php (index.blade.php extends master.blade.php)

    {{-- add any additional css for index page --}}
        $css->add('your/path/name', 'filename.css');


    {{-- remove any common css that i don't need in index page --}}
        $css->remove('your/path/name', 'commonFilename.css');




Please sign in or create an account to participate in this conversation.