问题
This is my controller:
return View::make('home.listings')
->with('listings', Listing::all());
Previously, I checked it on views like this: (and it worked on all my projects)
@if(!empty($listings))
//use foreach and show listings
@else
<h3>No listing is found.</h3>
@endif
This is my Listing model.
class Listing extends Eloquent {
public static $key = 'id';
protected $table = 'ilanlar';
public $timestamps = false;
}
Right now, it works when there is an entry in database. However, when there is not, it doesn't get to the else block. Because:
dd(!empty($listings)) //output: (boolean) true
And, when I output listings variable:
dd($listings) //outputs:
object(Illuminate\Database\Eloquent\Collection)[229]
protected 'items' =>
array (size=0)
empty
This is the reason why it doesn't reach else block, because Eloquent returns and object and it casts to true.
The problem is: I don't know why it returns an Eloquent collection. Previously it didn't. Am I overlooking something?
回答1:
The Collection object has a isEmpty() method, so you could use that:
@if(! $listings->isEmpty())
//use foreach and show listings
@else
<h3>No listing is found.</h3>
@endif
Alternatively, you can convert everything to an Array:
return View::make('home.listings')
->with('listings', Listing::all()->toArray());
And use everything as an array within your views:
@if(!empty($listings))
@foreach(listings as $listing):
<li>{{ $listing['name'] }}</li> <!-- Note $listing is treated as an array -->
@endforeach
@else
<h3>No listing is found.</h3>
@endif
回答2:
This is a known issue (if you'd call it an issue) the solution is to do @if(count($listings))
as you can see here
来源:https://stackoverflow.com/questions/19814401/laravel-4-s-all-method-started-to-return-eloquent-collection-lately-why