May 9th, 2022

Conditional callback execution using the Conditionable trait

Conditional callback execution using the Conditionable trait

Method chaining is a design technique that helps you simplify your code.
Your objects essentially return themselves, allowing you to "chain" successive operations together. On functions/methods that affect their parent object, method chaining works best.
Without returning a result, they normally set a variable or perform an action.

But what if you want to apply a callback if the given "value" is truthy or falsy ? Laravel comes with Illuminate\Support\Traits\Conditionable trait that provides two methods: when() and unless().

1use Conditionable;
2 
3$this->fooMethod()
4->barMethod()
5->when($this->fooBar(), function () {
6 //...
7})
8->someOtherMethod();

The callback above will be executed when $this->fooBar() returns true. If you want to check for falsy values you can use unless() which will execute it's callback if the checked value returns false.

Statamic Ninja

Comments

Marian Pop

PHP / Laravel Developer. Writing and maintaining @LaravelMagazine. Host of "The Laravel Magazine Podcast". Pronouns: vi/vim.

Subscribe to our newsletter

Get latest news, tutorials, community articles and podcast episodes delivered to your inbox.

Weekly articles
We send a new issue of the newsletter every week on Friday.
No spam
We'll never share your email address and you can opt out at any time.