To fetch sort data, we use latest, oldest and orderBy methods in laravel. The difference of these methods is: latest and oldest methods sort data according to the created_at column whereas orderBy methods sort data by the lexically.
Suppose, you have a table called post and you want to use latest methods, the syntax will be:
$posts = DB::table('posts')->latest()->get();
It will sort data based on created_at column. And the syntax of the oldest methods is:
$posts = DB::table('posts')->oldest()->get();
You can pass a column as a parameter. Let's say, I want, the data will be sorted based on title column. So, the syntax will be:
$posts = DB::table('posts')->latest('title')->get();
\\or
$posts = DB::table('posts')->oldest('title')->get();
On the contrary, orderBy sort data lexically.
$posts = DB::table('posts')->orderBy('title')->get(); \\ascending
\\or
$posts = DB::table('posts')->orderBy('title', 'desc')->get(); \\ descending
Thanks. happy coding!
Top comments (0)