Laravel Checking whether it has data or not from the model

可紊 提交于 2019-12-24 12:53:16

问题


I am receiving the data from url and sending it to the model to and then displaying in the model like this.

public function BlogDisplay($data=NULL)
    {
        $BlogData = BlogModel::where('BlogLink', '=', $data)->get();
        return View::make('Blogs', array('BlogData' => $BlogData));

And then in the view.

But to check whether it has the data or not I am doing that in the view like this:

<?php

   if($BlogData)
   {
     var_dump($BlogData);
     echo 'has data';
   }
   else
   {
     var_dump($BlogData);
     echo 'has no data';
   }
?>

But both of the it shows the array.

How can i check whether it given $data exist or not in the database.


回答1:


You are most likely getting back an Illuminate/Database/Eloquent/Collection object and the truthy check is coming back as true since the object is there. What you can do though is use the isEmpty() method built into that object.

http://laravel.com/api/4.2/Illuminate/Database/Eloquent/Collection.html#method_isEmpty

In your view:

@if ($BlogData->isEmpty())
    Nothing Here
@else 
    Got data!
@endif


来源:https://stackoverflow.com/questions/27660175/laravel-checking-whether-it-has-data-or-not-from-the-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!