Setting and Testing Cookies in a Livewire Component

I had a need today for a Livewire component to set a cookie, and wanted to test that it was actually set correctly.

Livewire includes support for reading cookies, but not for writing them.

And unfortunately, the redirect helper method doesn’t include any way to set a cookie.

Thankfully, Laravel provides a Cookie::queue() method that will attach set the cookie on the next outgoing response, and since Livewire method calls result in a HTTP response (unless you use the renderless attribute), the framework takes care of attaching the cookie for you:

Cookie::queue('name', 'value', $minutes);

However, I found it counterintuitive to test this behavior.

There is an assertCookie() method available when testing the component, but it always fails because we’re testing a Livewire component, not a request, and so the framework doesn’t attach the queued cookie(s).

My solution: use Cookie::queued() to retrieve the queued cookie, and then run assertions against that:

Laracon 2024: Caleb Porzio: Livewire Keynote

Caleb’s talk began with an unfortunate 30-minute delay caused by technical difficulties. He and Aaron Francis spent a bit of time entertaining the audience, and then Caleb took questions and answers from the audience until the equipment was ready.

He announced Flux, the official Livewire component library.

Under the hood, it uses a lot of web components, and everything he showed looked very well-designed and thought out.

I’m slightly hesitant to jump in and start using it, because I just recently spent not-insignificant time replacing another form component library that is no longer supported.

Because Caleb is charging money for this, I suspect it will remain a viable business and be supported longer than the open-source one I had used, but I still can’t bring myself to be as gung-ho about it as I’d like to be.

Laracon 2024: Philo Hermans: Livewire Beyond the Basics

Philo Hermans went deep into Livewire optimizations in his talk. A couple of key takeaways:

If your Livewire component calls an action that doesn’t need to re-render anything, you can skip re-rendering by using the [Renderless] attribute. I think I can find some immediate use cases for this.

For high-traffic apps with read replica databases, the sticky option can help guarantee consistency immediately after writes.

Optimistic UIs can improve perceived efficiency: use wire:loading.remove to immediately remove an element before the server round-trip has completed, so the app feels more snappy. I think I could also improve some UIs using this trick.