useful for say, laravel components, where often text can be handed by mistake e.g.
<x-mything render="false"/>
this will be string "false" and
if("false"){
// is truthy
}
the php way to handle this is here
https://stackoverflow.com/a/15075609/533426
is there a laravel way to do it?
the answer:
do
<x-mything :render="false"/>
is not the answer I'm looking for. I'm looking for a laravel way to cast string to boolean like in the linked post
CodePudding user response:
if(!filter_var($render, FILTER_VALIDATE_BOOLEAN)) {
// is falsy
}
Encapsulate this in a string macro. In the AppServiceProvider boot method add;
use Illuminate\Support\Str;
public function boot()
{
Str::macro('isFalsy', function ($str) {
return !filter_var($str, FILTER_VALIDATE_BOOLEAN);
});
}
now in code Str::isFalsy($render)
or in Laravel 9 str($render)->isFalsy()
or swap the logic and create an isTruthy() macro