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.
If you enjoyed this article, please consider supporting our work for as low as $5 / month.
Sponsor
Written by
Writing and maintaining @LaravelMagazine. Host of "The Laravel Magazine Podcast". Pronouns: vi/vim.
Get latest news, tutorials, community articles and podcast episodes delivered to your inbox.