Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting timestamps in Eloquent

Newbie here in Laravel 4. Say I have a model ("Activity") that has a timestamp column, along with other metadata. When I print it out in HTML, it is arranged from earliest to latest, which won't be ideal.I want to sort it from latest to earliest, because I'm going after an activity log.

Here's the code on the view:

@foreach ($activities as $activity)
<tr class="activity">
    <td>{{ $activity->timestamp }}</td>
    <td>{{ $activity->activity }}</td>
</tr>
@endforeach

Here's the controller code, which arranges these stuff:

public function getActivity()
{
        return View::make('app.website.activity', array('activities' => Activity::all()));
}

Is there anything I can do with Activity::all() to sort it out by time?

Thanks!

like image 749
Raffy Alcoriza Avatar asked Jul 12 '13 15:07

Raffy Alcoriza


People also ask

How to sort timestamp in Laravel?

If you are using the default laravel timestamps you can get the activities in descending order like this: Activity::orderBy('created_at','desc')->get(); If you have manually added your timestamp column you can get them in descending order like this: Activity::orderBy('timestamp','desc')->get();

How to sort in Laravel Eloquent?

To sort results in the database query, you'll need to use the orderBy() method, and provide the table field you want to use as criteria for ordering. This will give you more flexibility to build a query that will obtain only the results you need from the database.

What is the use of timestamps in laravel?

Timestamps allows you to automatically record the time of certain events against your entities. This can be used to provide similar behaviour to the timestamps feature in Laravel's Eloquent ORM.


1 Answers

If you are using the default laravel timestamps you can get the activities in descending order like this:

Activity::orderBy('created_at','desc')->get();

If you have manually added your timestamp column you can get them in descending order like this:

Activity::orderBy('timestamp','desc')->get();

Hope this is what you are looking for.

like image 105
Altrim Avatar answered Nov 03 '22 23:11

Altrim