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

Issue

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 class="form-group">
                    <label for="name">Name</label> <br>
                    <input type="text" name="Name" class="form-control" value="{{$survey->name}}">
                </div>

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

Solution

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 class="form-group">
                    <label for="name">Name</label> <br>
                    <input type="text" name="Name" class="form-control" 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!

Answered By – MysticSeagull

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published