Input:.get('X') as string only

I got a search form and got a report that if you manipulate the url, you generate an error:

search?searchterm[0]=TEST

Internally, I performed this action:

        $searchTerm = trim(Input::get('searchterm'));
        if (!empty($searchTerm) || $searchTerm === "0")
            $this->searchTerm = $searchTerm;

The variable searchTerm is of type string and will be further processed lateorn.
In order to avoid the TypeError which cause the problem, I rewrote this to the following:

        $searchTerm = Input::get('searchterm');
        if (
            is_string($searchTerm)
            && (!empty($searchTerm) || trim($searchTerm) === "0")
        )
            $this->searchTerm = $searchTerm;

Now I wonder:
I got multiple inputs like this so a better way is welcome in order to avoid all the rewritten code. Sure I can simply write a method for this, but I wonder if something exists already out of the box which I simply overlook…

Couldnt find an doc which I could use here…

Thx for the help :slight_smile:

This would do it in a compact way:

$searchTerm = trim(((array) Input::get('searchterm'))[0] ?? '')
2 Likes