Dev Notes

Software Development Resources by David Egan.

Push to Named Stacks in Laravel Blade


Blade, Laravel
David Egan

Laravel blade usefully allows you to push to named stacks which can be rendered in different views. You can push either inline code, or a call to an external file.

Push to the Stack

You can push to a given stack multiple times. Pushing is achieved by wrapping your code in @push. This code triggers an alert confirmation if a delete form is submitted. The code is only required on one view, so pushing to the stack looks like a good option:

@push('scripts-footer')
  <script>
    $(function () {
      $('.data-delete').on('click', function (e) {
        var resourceTitle = $(this).data('title');
        if (!confirm('Are you sure you want to delete ' + resourceTitle + '?')) return;
        e.preventDefault();
        $('#form-delete-' + $(this).data('form')).submit();
      });
    });
  </script>
@endpush

This method can be quite nice for small bits of functionality as you can work on your script with the markup in front of you (you don’t have to remember data attributes etc). You could abstract your script out to an external file, and push a call to this file to the stack:

@push('scripts-footer')
    <script src="/build/js/are-you-sure.js"></script>
@endpush

Render the Stack

Then in another template, output the stack. For example, in the blade template for the footer:

@stack('scripts-footer')

More Stuff to Explore

Apparently if you @push from inside a form using model binding, then you have access to that context. I haven’t tried this but it looks interesting.

References


comments powered by Disqus