简体   繁体   中英

Laravel how do I use forelse() on table?

I am using a forelse statement on a table as:

@forelse($message->content->suggestions as $suggestion)
                <td>
                    @foreach ($message->content->suggestions as $suggestion)
                    <span class='badge badge-info'>{{($suggestion->reply->text)}}</span>
                    @endforeach
                </td>
                @empty
                    <em> - </em>
                @endforelse

My goal is to check if the table has data called suggestions then run the foreach() however if it's empty just show "-" this is my first time using forelse and wanted to learn it:) If I can't do it this way can someone share how to do it with IF statement instead?

Can you see what I am doing wrong, if I open a table without suggestions I just get a error instead of "-"

Table giving error looks like:

"id" => "3d0ef00c-0edd-4d8b-ad1c-27e92e29c469"
"method" => "rcs"
"msisdn" => 64224603
"direction" => "mt"
"type" => "text"
"status" => "delivered"
"content" => "{"text":"Dial a number"}"
"suggestion_id" => null
"created_at" => 1591669329
"updated_at" => 1591669333
"deleted_at" => null

I would do something like this...

@if(!empty($message->content->suggestions))
    // There is are suggestions
    @foreach($message->content->suggestions as $suggestion)
        <span class='badge badge-info'>{{ $suggestion->reply->text }}</span>
    @endforeach
@else
    // No Suggestions
    <span class='badge badge-info'>-</span>
@endif

This checks if suggestions are available and if so loops through them, if not, displays a -. Also assuming your relationships are setup correctly.

Thry this. I have used this way in one of my project.

@forelse($message->content->suggestions as $suggestion)
<td>

<span class='badge badge-info'>{{($suggestion->reply->text)}}</span>

</td>
@empty
 <span> - </span>
@endforelse

Try this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM