In this episode, we dive into the new when()
helper in Laravel and see why it's a handy tool, especially inside Blade templates—including when working with Livewire. We kick things off by exploring the syntax in a tinker session: pass in a boolean condition as the first argument and either a value, string, or closure as the second. It's super simple—if the condition is true
, you get that value back; if it's false
, you get null
.
Next, we switch over to a Blade template to see some practical examples. One cool use is making a div
content-editable only under certain conditions using when()
directly, which keeps your Blade code clean and tidy, instead of using messy @if
statements everywhere. We also touch on when not to use when()
: for things like the disabled
attribute on inputs, Blade already has a nicer directive (so stick to that instead).
To push things further, we jump into a Livewire example by setting up a simple user index component. Imagine you want a list of users, and only admins can click and trigger a Livewire action (like opening an edit modal). Using the when()
helper, you can conditionally add the wire:click
attribute, making the code much easier to read.
We also briefly talk about string escaping and how to use raw output so when()
works as intended inside HTML attributes. There are tips for combining when()
with class helpers (like giving a cursor pointer to clickable elements if the condition is met), and a quick nod to running npm run dev
for any front-end changes.
All up, you’ll see how when()
helps write cleaner, more expressive, and less repetitive Blade and Livewire code, especially for conditional attributes and classes!