-1

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

Toskan
  • 13,911
  • 14
  • 95
  • 185
  • 1
    The answer you are not looking for is the right answer, that's just the way Laravel components work. PHP expressions and variables should be passed to the component via attributes that use the ":" character as a prefix. – Karlo Mar 24 '22 at 18:52
  • @Karlo well that isn't good either as then 1, "1", "true", "yes" will not be handled correctly. Say if you do `` if you aren't 100% sure what type of truethy or falsy value is there. – Toskan Mar 25 '22 at 11:40
  • 1
    filter_var is the correct approach as it checks multiple different ways of saying false or true. Not sure what you are expecting as a 'laravel way' when there is already a php function that perfectly accomplishes the goal. – Snapey Mar 25 '22 at 17:11
  • @Snapey what does the implementation of `Str::replace();` actually do? call str_replace? what does laravels `str_contains` do? call `mb_strpos !== false`? those are just convenience functions that make it easier to understand. When I want to transform a boolean, there is no direct mental connection from boolean to having to use `filter_var` and `FILTER_VALIDATE_BOOLEAN`. If you still refuse to understand you become a bad faith actor here. – Toskan Mar 26 '22 at 12:40
  • Its used so infrequently as to not justify a helper. Feel free to create a pull request to the framework. – Snapey Mar 26 '22 at 13:06

1 Answers1

1
    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

Snapey
  • 3,604
  • 1
  • 21
  • 19