Skip to content

Instantly share code, notes, and snippets.

@muath-ye
Created September 24, 2023 18:07
Show Gist options
  • Save muath-ye/ad708860432f725867a36f7425569e2e to your computer and use it in GitHub Desktop.
Save muath-ye/ad708860432f725867a36f7425569e2e to your computer and use it in GitHub Desktop.
A Laravel helper to call a callable function conditionally
if (! function_exists('when')) {
/**
* Execute the given callback function if the condition is true.
*
* @param bool $condition
* @param callable $function
* @return mixed|null
*/
function when(bool $condition, callable $function)
{
if ($condition) {
return $function();
}
return null;
}
}
@muath-ye
Copy link
Author

Here is an update for the function

if (! function_exists('when')) {
    /**
     * Execute the given callback function if the condition is true.
     *
     * @param  bool  $condition
     * @param  callable  $function
     * @param  mixed  $default
     * @return mixed|null
     */
    function when(bool $condition, callable $function, mixed $default = null)
    {
        return $condition ? $function() : $default;
    }
}

@muath-ye
Copy link
Author

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment