DEV Community

loading...
Cover image for How to use Laravel Blade @stack('scripts')

How to use Laravel Blade @stack('scripts')

abrardev99 profile image Abrar Ahmad ・2 min read

I see a lot of people are not getting benefits from laravel blade fully. One of blade directive @stack('scripts') is very helpful when you have javascript need to execute in the child page.

I create a fresh Laravel installation to demo an example. I have to make auth scaffolding with laravel/ui package because I'm using Laravel 6.

What is stack('anyname') directive

Stack directive as self-explaining it stacks the scripts where you want to stack them.

How to use

Let's say you have a master view and child views. And you have some javascript operations specifically related to child page may be an Ajax request. Now it is not good practice to put every javascript on the master page. It will slow down the speed because it is executing child pages scripts that don't need.

So what we need to do, in our master page just before closing body tag make @stack like below code.

<!-- Scripts -->
<script src="{{ asset('js/app.js') }}" ></script>
@stack('child-scripts')

Now in our child page, let's say home, you have alert specific to the child, how to do that

@extends('layouts.app')
@section('content')
<div>I'm child</div>
@endsection

@push('child-scripts')
<script>
alert('I\'m coming from child')
</script>
@endpush

And alert is coming from child
Alt Text

My thoughts:

It is a very clean way of writing javascript.
It improves code readability and performance.
And it will always go to the end of the page as recommended where you put @stack, directive does not matter from where push is coming.

Discussion

pic
Editor guide
Collapse
slowwie profile image
Michael

The problem with @stack and push is, you can replicate it.
When push would not end up repeating the same script, this would be a crazy powerfull tool.

Collapse
leettaylor profile image
Lee Taylor

There's now a @once component in Laravel 7.2.x that would be useful for achieving that. So you could do something like this...

@push('scripts')
    @once
        <script src="{{ global_asset(mix('/js/example.js')) }}"></script>
    @endonce
@endpush
Enter fullscreen mode Exit fullscreen mode
Collapse
abrardev99 profile image