php

Laravel 9 Eloquent orderBy Query

Laravel 9 has an excellent feature named Eloquent. It is an ORM (object-relational mapping), and it helps users to communicate between applications to databases very easily. In Laravel 9, when we use Eloquent, it works as a “Model” and communicates with the database. It helps you get data from the table in the database.

In Laravel 9, there are multiple ways to get data by order. One way is shown below:

->orderBy

Today, we will learn how to use orderBy in Laravel and when to use it.

orderBy in Laravel

In Laravel 9, when we need to sort our data collection by descending or ascending order from the database. Then we need to use an orderBy in the Laravel query. In the regular MySQL queries, we use it as shown below:

Select * from ‘collection’ where ‘status’ = ‘something’ order by ‘collection_id asc

But, Laravel has a different way of assigning the following:

->orderBy(‘collection_id’, ‘asc’)

Project requirements are given below:

  • MySQL 8.0+
  • MariaDB 10.2+
  • PHP 8.1

Here is an example of defining the orderBy query:

  1. Process1. Create an orderBy Project
  2. Process 2. Database Connection
  3. Process 3. Apply the orderBy Method
  4. Process 4. Run and Test the orderBy Project

Process 1. Create an OrderBy Project

Now, we need to run this command to create this project:

Composer create-project Laravel/Laravel orderByProject

Process 2. Database Connection

Open the .env file on the orderByProject project and add new database details.

Here’s the following code:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=Database name
DB_USERNAME=Database user name
DB_PASSWORD=Database password

Check the following image:

Process 3. Apply the orderBy Method

Before we apply orderBy to our project, we will need to create a database table for our database. For that, we will create a table called “CollectionList”. We have to run the following command to create the table:

php artisan make:modelCollectionList -m

The code is provided below:

return new class extends Migration
{

    public function up()
    {
Schema::create('collection_lists', function (Blueprint $table) {
            $table->id();  //auto increment
            $table->timestamps();
        });
    }

    public function down()
    {
Schema::dropIfExists('collection_lists');
    }
};

I need to add these two to the following code:

$table->string('name')->nullable();
$table->longText('details')->nullable();

Let’s migrate the data to the database. Run the following command:

php artisan migrate

Next, create a controller to manage the function with the query.

Here, we created a controller named “CollectionList” for our OrderBy project. We need to run this command to create the following project:

php artisan make:controllerCollectionList

The code should look like this:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class CollectionList extends Controller
{
    //
}

Now, I need to create a function in the controller:

The name of the function isallCollection.

After adding this function, it should look as follows:

<?php

namespace App\Http\Controllers;

use App\Models\CollectionList as ModelsCollectionList;
use Illuminate\Http\Request;

class CollectionList extends Controller
{
    public function allCollection()
    {
        $alldata = ModelsCollectionList::orderBy("id", "asc")->get();

        return view('welcome',compact('alldata'));
    }
}

For the get() method, we need to use data in ascending order:

   $alldata = ModelsCollectionList::orderBy("id", "asc")->
get();

To get the data in descending order, we need to use the following:

   $alldata = ModelsCollectionList::orderBy("id", "desc")->get();

Add a view under the resource\View folder called welcome.blade.php.

<html>

<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<!------ Include the above in your HEAD tag ---------->

<head>

<div class="container">
<div class="row">
<div class="col-md-12 text-right">

</div>
</div>
            @foreach($alldata as $each_article)
<div class="col-md-12">
<h1>{{$each_article->name}}</h1>

<hr>

</div>
            @endforeach
</div>


</html>

Now, we need to add a route in routes\web.php:

Route::get('/collection', [CollectionList::class, 'allCollection'])->name('allCollection');

Process 4. Run and Test the orderBy Project

Next, we need to run the following:

php artisan serve

For the ascending order, the project will look like the following image:

For the descending order, it looks like the following image:

Conclusion

In this article, we created this Laravel Query project with Laravel 9. Creating a data table Laravel orderBy is very useful. We hope this orderBy project example will help you to understand the orderBy in Laravel 9.

About the author

Rakhibul Hasan

This is Rakhibul Hasan CEO and Founder of Clipping Path Creative Inc. We provide 100% handmade photo editing services to use Adobe Photoshop. Our services are Clipping path, Background removal, Color correction, Photo retouching, Car photo editing, drop shadow etc. Also we offer an image as a trial to judge our quality. So contact us and get instant reply.