Home  >  Q&A  >  body text

Laravel Blade: compare string to object

<p>I ran into a strange issue when comparing an object to a string in a Laravel blade file. </p> <p>I have a variable that can be a string ("N/A") or an object depending on the result of the database query, and I have the following conditional check: </p> <pre class="brush:php;toolbar:false;">@if ($a_string_name == 'N/A')</pre> <p>If an object is returned, for most users this condition will fail and execution of the else statement will continue. </p> <p>But for one specific case (I don't have enough information to say how to reproduce this), this condition throws an error: </p> <pre class="brush:php;toolbar:false;">Method Illuminate\Support\Collection::__toString() must return a string value</pre> <p>I can't figure out what's going wrong or if this is a laravel/browser specific issue. </p> <p>PHP v7.4.22, laravel v6.0</p>
P粉797855790P粉797855790436 days ago531

reply all(1)I'll reply

  • P粉407936281

    P粉4079362812023-09-02 10:10:56

    Based on your question above, I think you want to check if a variable is set with a given value. In your case, try using @if(isset($a_string_name)).

    We usually use two PHP methods to check variables.

    How to check whether a variable is defined in PHP? The isset() function checks if a variable is set, which means the variable must be declared and not NULL. The function returns true if the variable exists and is not NULL, false otherwise.

    How to check if a given variable is empty? The empty() function checks whether a variable is empty. The function returns false if the variable exists and is not empty, otherwise it returns true. The following values ​​evaluate to null: 0.

    Hope this helps.

    reply
    0
  • Cancelreply