How to Use @push and @stack in Blade Templates
In Laravel Blade, use
@push('stackName') to add content to a named stack and @stack('stackName') to output all pushed content in that stack. This helps you inject scripts or styles from child views into specific places in your layout.Syntax
The @push('stackName') directive adds content to a named stack, and @endpush closes it. The @stack('stackName') directive outputs all content pushed to that stack.
This allows you to collect pieces of content from different views and render them together in one place, usually in your layout.
blade
@push('scripts') <script src="/js/custom.js"></script> @endpush <!-- Later in the layout --> @stack('scripts')
Example
This example shows how a child view pushes a script to the scripts stack, and the layout outputs all pushed scripts at the bottom of the page.
blade
<!-- resources/views/layout.blade.php -->
<html>
<head>
<title>My App</title>
</head>
<body>
<h1>Welcome</h1>
@yield('content')
<!-- Output all pushed scripts here -->
@stack('scripts')
</body>
</html>
<!-- resources/views/child.blade.php -->
@extends('layout')
@section('content')
<p>This is the child content.</p>
@push('scripts')
<script>
console.log('Script from child view');
</script>
@endpush
@endsectionOutput
<html>
<head>
<title>My App</title>
</head>
<body>
<h1>Welcome</h1>
<p>This is the child content.</p>
<script>
console.log('Script from child view');
</script>
</body>
</html>
Common Pitfalls
- Forgetting to use the same stack name in both
@pushand@stackcauses no output. - Using
@pushoutside of a section or layout may not work as expected. - Multiple
@pushcalls with the same stack name append content in order; mixing order can cause confusion.
blade
<!-- Wrong: Different stack names --> @push('scripts') <script>console.log('Hello');</script> @endpush <!-- Layout uses --> @stack('js') <!-- This will output nothing because stack names differ --> <!-- Right: Matching stack names --> @push('scripts') <script>console.log('Hello');</script> @endpush @stack('scripts')
Quick Reference
- @push('stackName'): Start adding content to a named stack.
- @endpush: End the push block.
- @stack('stackName'): Render all content pushed to the named stack.
- Use stacks to inject scripts, styles, or other content from child views into layouts.
Key Takeaways
Use @push to add content to a named stack and @stack to output it in your layout.
Ensure the stack names match exactly between @push and @stack.
Stacks help organize scripts or styles from multiple views into one place.
Multiple pushes to the same stack append content in order.
Always place @stack in your layout where you want the pushed content to appear.