繁体   English   中英

需要检查laravel中的对象是否为空

[英]Need to check if an object is empty in laravel

我通过做一个雄辩的查询来创建一个视图,然后将它传递给 Blade。

@if($contacts != null)
//display contacts
@else
You dont have contacts
@endif

然而,它总是假设 $contacts 有一些东西,即使查询没有给我任何东西。

我做了dd($contacts)并得到:

Collection {#247 ▼
  #items: []
}

我如何检查它是否为空?

如果它是 Eloquent 集合,就像您的示例中那样,您可以使用 isEmpty 集合辅助函数;

@if(!$contacts->isEmpty())
//display contacts
@else
You dont have contacts
@endif

集合文档

有几种方法:

if (!empty($contacts))

if (!contacts->isEmpty())

if (count($contacts) > 0)

if ($contacts->count() > 0)

您的 Eloquent 查询返回一个结果数组,因此您可以使用count

@if(count($contacts) > 0)
//Display contacts
@else
//No contacts
@endif

您的$contacts是空的。 Bcoz 您的查询无法获取数据。 一旦您的查询无法获取数据,它就会返回一个空的 arrya。 所以检查一下

    @if($contacts->isEmpty())
    {{ 'Empty' }} 
    @else
   {{ 'you have data' }}
    @endif

您可以使用blank($contacts)
帮手 Laravel:空白

您必须执行以下操作:

在您的“ ContactController ”视图中:

public function index()
{
   $contacts = Contact::all();
   return view('page.index', compact('contacts'))
}

稍后查看“ index.blade.php ”:

@if (collect($contacts)->isEmpty()) {{-- remember that $contact is your variable --}}
   <p>There is no record available at this time</p>
@else
   @foreach($contacts as $contact)
      {{$contact->name_contact}}
   @endforeach
@endif

现在,我想你有一个名为Contact的模型

if(count($profiles) > 0){
            return redirect()->action('NameController@name');
        }else{
            return view('user');
        }

这在控制器中也能正常工作

我在我的助手类中添加了全局方法

function isNullOrEmpty($value)
{
    return is_null($value) || empty($value);
}

如果它在控制器内,这将有所帮助

if(empty($query) {
     //do something
}else{
//do some stuff
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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