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

Laravel 5.8:如何用IF&ELSE判断MySQL表字段空值及表是否为空

解决Laravel 5.8中的两个数据库判断问题

1. 正确判断模型字段是否为NULL/非NULL

你原来代码里的@if($showaccounts->id == !NULL)写法是错误的——!NULL在PHP中等价于布尔值true,你实际是在判断$showaccounts->id == true,这完全偏离了你要检查字段是否为NULL的需求。

你尝试过的is_null()和=== NULL其实是有效的判断方式,只是你遇到的问题不在判断本身,而是循环逻辑的问题:如果$accounts集合为空,@foreach根本不会执行,所以循环体内的@else永远不会被渲染出来。

先给你正确的字段判断写法:

  • 判断字段为NULL:
    @if(is_null($showaccounts->id))
        <!-- 字段为NULL时的逻辑 -->
    @endif
    
    或者
    @if($showaccounts->id === null)
        <!-- 字段为NULL时的逻辑 -->
    @endif
    
  • 判断字段非NULL:
    @if(!is_null($showaccounts->id))
        <!-- 字段非NULL时的逻辑 -->
    @endif
    
    或者
    @if($showaccounts->id !== null)
        <!-- 字段非NULL时的逻辑 -->
    @endif
    

2. 判断数据库表(查询集合)是否为空

你的核心需求是:当没有账户数据时显示"No Results",但原来把@else放在@foreach循环体内是错误的——如果$accounts是空集合,循环根本不会运行,@else永远不会触发。

正确的做法是先判断集合是否为空,再决定渲染数据还是无结果提示:

@if($accounts->isNotEmpty())
    @foreach($accounts as $showaccounts)
        <!-- 可选:如果需要过滤掉id为NULL的记录,在这里加判断 -->
        @if(!is_null($showaccounts->id))
            <div class="list-item" data-id="item-11">
                <span class="w-40 avatar circle blue"> 
                    <img src="{{ $showaccounts->image }}" alt=".">
                </span> 
                <div class="list-body">
                    <a href="app.message.php" class="item-title _500">{{ $showaccounts->username }}</a> 
                </div> 
            </div>
        @endif
    @endforeach
@else
    <div class="no-result"> 
        <div class="p-4 text-center">No Results</div> 
    </div>
@endif

额外优化:提前在查询阶段过滤无效数据

如果你不需要显示id为NULL的账户,建议直接在控制器的查询中过滤掉,这样视图逻辑会更简洁:

// 在控制器中
$accounts = Account::whereNotNull('id')->get();

此时视图里可以直接循环,无需再判断字段是否为NULL:

@if($accounts->isNotEmpty())
    @foreach($accounts as $showaccounts)
        <div class="list-item" data-id="item-11">
            <span class="w-40 avatar circle blue"> 
                <img src="{{ $showaccounts->image }}" alt=".">
            </span> 
            <div class="list-body">
                <a href="app.message.php" class="item-title _500">{{ $showaccounts->username }}</a> 
            </div> 
        </div>
    @endforeach
@else
    <div class="no-result"> 
        <div class="p-4 text-center">No Results</div> 
    </div>
@endif

为什么你之前的尝试没生效?

你之前把@else放在循环体内,但当$accounts为空时,循环根本不会执行,所以"No Results"永远不会显示。另外,empty($showaccounts->id)虽然能识别NULL,但如果id是0这类有效值也会被判定为空,所以不建议用它来判断NULL,优先选择is_null()或严格等于=== null。

内容的提问来源于stack exchange,提问作者Fazıl Akbulut

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 07:35:47