Laravel Blade @prepend Directive

Tutorials

February 11th, 2017

blade-prepend.png

In version 5.4 Laravel added a new components and slots feature that simplifies building HTML elements into reusable areas.

As an example of how this features works pretend you have a layout.blade.php file that includes this:

1<ul id="sidebar">
2 @stack('sidebar')
3</ul>

Now when you want to insert data into this section from a sub-view you can add:

1@push('sidebar')
2 <li>Sidebar list item</li>
3@endpush

Once this is rendered in the browser the results are an unordered list:

1<ul id="sidebar">
2 <li>Sidebar list item</li>
3</ul>

Now since v5.4.10 a new prepend directive has been which allows you to push an item to the front of the stack before it’s rendered.

For example:

1@push('sidebar')
2 <li>Sidebar list item</li>
3@endpush
4
5@prepend('sidebar')
6 <li>First Sidebar Item</li>
7@endprepend

Now, the results will be:

1<ul id="sidebar">
2 <li>First Sidebar Item</li>
3 <li>Sidebar list item</li>
4</ul>

This will be great in those situations where you need to push items to the front of the stack.

Filed in:

Eric L. Barnes

Eric is the creator of Laravel News and has been covering Laravel since 2012.