edmond edmond - 3 months ago 40
PHP Question

How to order my foreach in laravel blade

I am using a hasMany in my Model class to retrive the clients notes, how ever i want to order these notes by the latest date created in laravel blade template.

My code is below and im getting an error on this.

Please advice me..

@foreach($clients->notes->orderBy('created_at', 'desc') as $note)
<table class="table table-bordered">
<td class="col-xs-2 col-md-2"><b>Created On:</b> {{ date('d/m/y', strtotime($note->created_at)) }} <b>&#64;</b> {{ date('g:i A', strtotime($note->created_at)) }} </td>
<td class="col-xs-14 col-md-12">{{ $note->notes }}</td>


Guessing, because you haven't told us what error you're getting, but:

$clients->notes is an already-fetched collection of results. $clients->notes() is a query builder that you can apply further logic like ordering or additional criteria to.

You likely want:

$clients->notes()->orderBy('created_at', 'desc')->get()

but you should do that in the controller and pass it to the view instead of having the query directly in the Blade template.

(You can alternatively use Laravel's collection functions on $clients->notes, including the sortBy() function).