Reputation: 3893
I want to sort/order my data by its release_date
but I get an error I don't understand:
In my Controller I have:
public function index() {
$releases = Release::orderBy('release_date', 'desc');
return view('pages.index')->with('releases', $releases);
}
and in my view file I have this:
@if (count($releases) > 0)
@foreach ($releases as $release)
<div>
<p>{{$release->artist}} - {{$release->album_title}} <span>ReleaseDate: {{$release->release_date}}</span></p>
</div>
@endforeach
@endif
This returns the error:
count(): Parameter must be an array or an object that implements Countable
What does this mean? Can someone help me out?
Upvotes: 1
Views: 104
Reputation: 775
Try this code:
public function index()
{
$releases = Release::orderBy('release_date', 'desc')->get();
return view('pages.index')->with('releases', $releases);
}
The reason you code wasn't working before is because orderBy
won't perform the query, it will simply add to it. In this case you need to chain on get()
at the end in order to perform the query and get the results otherwise you will just get an instance of the query builder.
Upvotes: 1
Reputation: 294
Change Controller
public function index() {
$releases = Release::orderBy('release_date', 'desc')->get();
return view('pages.index',compact('releases');
}
change View
@if ($releases->count() > 0)
@foreach ($releases as $release)
<div>
<p>{{$release->artist}} - {{$release->album_title}} <span>ReleaseDate: {{$release->release_date}}</span></p>
</div>
@endforeach
@endif
Upvotes: 0