Home > Enterprise >  Laravel 8 pass variable to be used in foreach loop for comparison
Laravel 8 pass variable to be used in foreach loop for comparison

Time:06-13

I'm trying to pass a predefined variable with a value into the @if part of the statement for comparison. This is for Laravel v8.0 on the blade.php. It only works if I hardcoded the value in it but not through the variable $value. I would need to have a placeholder variable to pass the value for comparison, as it will be inputted from user. Hence may I know what is the proper way to declare the variable as in this case? Sorry I'm just starting learning Laravel. Thanks for your help.

Eg:

    $value = "abc123";

    @foreach($surveys as $survey)
        @if($survey->Unit_code == {{$value}})
            
            <form action="" method="">
                @csrf 
                <div >
                    <label for="name">Name</label> <br>
                    <input type="text" name="Name"  value="{{$survey->name}}">
                </div>

                <input type="submit" value="Save">
            </form>
        @endif
    @endforeach 

CodePudding user response:

Just so this is in an answer form for other users that encounter this problem as a developer just learning laravel; the issue here is there was an output to the dom using {{}} where the blade directives (things that start with @) use the PHP vars as is an example of this would be as follows:

@if($survey->Unit_code == $value)

the other issue he was having, in this case, is assigning raw PHP on the blade file, this works the same way. Although, to add raw PHP to the dom you would use the @php directive

    @php
        $value = "abc123";
    @endphp
    @foreach($surveys as $survey)
        @if($survey->Unit_code == $value)
            
            <form action="" method="">
                @csrf 
                <div >
                    <label for="name">Name</label> <br>
                    <input type="text" name="Name"  value="{{$survey->name}}">
                </div>

                <input type="submit" value="Save">
            </form>
        @endif
    @endforeach

if the data of $value needed to be completely dynamic based on the backend then I would recommend passing it to the blade file via the view() function instead and assigning the value there or as nullable on the first pass of the function. Hope that helps!

CodePudding user response:

You dont have to use {{ }} in @if condition .

When you use @if( ) everthing inside of it can translate into php .

So , you instead of using :

 @if($survey->Unit_code == {{$value}})

Use :

 @if($survey->Unit_code == $value )

Hope that works .

  • Related