laravel order by asc and desc example

In this section, we will see use of Order By asc and desc in Laravel . you can use 5+,6,7,8, 9.


Order By asc Example

<?php

namespace App\Http\Controllers;

use App\Models\Post;
use Illuminate\Http\Request;

class PostController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {

        $posts = Post::orderBy("id", "asc")->get();

        return $posts;
    }


Now We can see all Post are ascending order but ID base

in this image you can see it short by ID like (1,2,3,4,5) we can also short by orderBy("name", "asc"), orderBy("date", "asc") short Field


Order By desc Example

order by desc is opposite of order by asc it show by last or descending order

public function index()
    {

        $posts = Post::orderBy("id", "desc")->get();

        return $posts;
        // return view('posts.index', compact('posts'));
    }


you can see it short by last ID like (22,21,20,19,18) we can also short by orderBy("name", "desc"), short Field