We can load on the demand page in laravel using @push() and @stack blade directive. Assume you would like to load some css or script only for some pages then @stack and @push is for you. Laravel @stack and @push allow us to load script and css for a single file for on-demand loading.

In this tutorial, I will show you how to use @stack and @push blade directive in Laravel 9 application. The blade allows you to push to named stacks which can be rendered somewhere else in another view or layout. This can be useful for specifying any JavaScript and css libraries required by your child views:

See the example of laravel stack push implementation example:

resources/views/layouts/app.blade.php

<!doctype html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>{{ config('app.name', 'Laravel') }}</title>
    @stack('style')
</head>
<body>
    <div id="app">
        <nav class="navbar navbar-expand-md navbar-light bg-white shadow-sm">
            <div class="container">
                <a class="navbar-brand" href="{{ url('/') }}">
                    Laravelia
                </a>
                <div class="collapse navbar-collapse" id="navbarSupportedContent">
                    <!--Header section -->
                </div>
            </div>
        </nav>
        
        <!--Content section -->
        <main class="py-4">
            @yield('content')
        </main>
    </div>
    @stack('script')
</body>
</html>

 

And now if we want to load css and script for welcome page, that you do not want to load globally then follow this example code for welcome page:

resources/views/welcome.blade.php

@extends('layouts.app')

@push('style')
<!--Your CSS Assets or Code Goes Here -->
@endpush

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
               
            </div>
        </div>
    </div>
</div>
@endsection

@push('script')
<!--Your JavaScript Assets or Code Goes Here -->
@endpush

 

Read also: How To Create Master Layout In Laravel?

 

Conclusion

I have tried to discuss the clear concept of stack laravel and push script laravel. Now we know how to create push css in laravel and laravel stack push example. Hope this laravel stack push example tutorial will help you.