Laravel Blade Once Component

News

August 19th, 2020

blade-once.jpg

As of Laravel 7.25, Blade now includes a new @once component that will only render the items within the tags one time. It’s a little hard to explain and much easier to show with an example, and here is one Taylor included in the original pull request:

1Component content here...
2
3@once
4 <script>
5 This will only be included in the template once even if component is rendered multiple times.
6 </script>
7@endonce

Then Mohamed Said followed up with another example:

1@once
2<template id="recieptsTemplate">
3 <div class="flex flex-column items-center">
4 <div class="w-1/2" data-reciept="paid_at"></div>
5 <div class="w-1/4" data-reciept="amount"></div>
6 </div>
7</template>
8@endonce
9
10<div data-id="receipts" class="divide-y divide-grey-300"></div>

This component renders a list of receipts. The template for the receipt has to be rendered once in the entire page while the component itself can be used multiple times.

This once feature is now pulled into Laravel starting with v7.25 so you can start using it today.

Filed in:

Eric L. Barnes

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