You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Laravel foreach循环中按数据库值显示固定对应状态文本?

Solution for Status Text Display in Laravel Table

Got it, let's adjust your table view to show the correct status text based on the database value. You can use either a ternary operator (for concise code) or Laravel's Blade @if directive (for more readability) to handle this condition.

Option 1: Using Ternary Operator (Concise)

This is the shortest way to implement the condition directly in the table cell:

<table class="table table-striped">
    <thead>
        <tr>
            <th>Patient Name</th>
            <th>Date of Birth</th>
            <th>Gender</th>
            <th>Phone</th>
            <th>Email</th>
            <th>Address</th>
            <th>Status</th>
        </tr>
    </thead>
    <tbody>
        @foreach($posts as $post)
        <tr>
            <td>{{ $post->patient_name }}</td>
            <td>{{ $post->dob }}</td>
            <td>{{ $post->gender }}</td>
            <td>{{ $post->phone }}</td>
            <td>{{ $post->email }}</td>
            <td>{{ $post->address }}</td>
            <!-- Modified status column -->
            <td>{{ $post->status == 1 ? 'active' : 'inactive' }}</td>
        </tr>
        @endforeach
    </tbody>
</table>

Option 2: Using Blade @if Directive (More Readable)

If you prefer more explicit code (great for team collaboration and readability), use Blade's conditional directives:

<table class="table table-striped">
    <thead>
        <tr>
            <th>Patient Name</th>
            <th>Date of Birth</th>
            <th>Gender</th>
            <th>Phone</th>
            <th>Email</th>
            <th>Address</th>
            <th>Status</th>
        </tr>
    </thead>
    <tbody>
        @foreach($posts as $post)
        <tr>
            <td>{{ $post->patient_name }}</td>
            <td>{{ $post->dob }}</td>
            <td>{{ $post->gender }}</td>
            <td>{{ $post->phone }}</td>
            <td>{{ $post->email }}</td>
            <td>{{ $post->address }}</td>
            <td>
                @if($post->status == 1)
                    active
                @else
                    inactive
                @endif
            </td>
        </tr>
        @endforeach
    </tbody>
</table>

Bonus: Add Visual Styling (Optional)

To make the status more noticeable, you can pair it with Bootstrap badges:

<td>
    @if($post->status == 1)
        <span class="badge bg-success">active</span>
    @else
        <span class="badge bg-secondary">inactive</span>
    @endif
</td>

Both core options will check the status field: when it equals 1, it displays "active"; for any other value, it shows "inactive".

内容的提问来源于stack exchange,提问作者BSH ICT

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 19:47:40