By adding dynamic body class to html pages we can get the flexibility of easily modifying the look of the each page by using css without modifying the html markup.So here i am gonna teach you how to add dynamic body class to HTML in your laravel application with simple steps.
We are going to write the function which will explode the current URI segments and it will filter and remove the unnecessary data like digits and it will build more meaning full classes for HTML body based on the current URI.Let’s start
Create a file called App/Helpers/Helper.php. and past the below code and autoload it with your composer by adding file path to composer.json
EX:
"autoload": {
"files": [
"app/Helpers/Helper.php"
]
},
function bodyClass() { $body_classes = array(); $class = ""; foreach ( \Request::segments() as $segment ) { if ( is_numeric( $segment ) || empty( $segment ) ) { continue; } $class .= ! empty( $class ) ? "-" . $segment : $segment; array_push( $body_classes, $class ); } return ! empty( $body_classes ) ? implode( ' ', $body_classes ) : NULL; } }
How to Use
In you layout , add the function as shown below
NOTE: Don’t forgot to update autoloader by running (composer dump-autoload).