Custom Laravel Eloquent Collections – Fast tips

Valerio Barbera

Eloquent is one of the most powerful components of the Laravel framework. It’s an Object-Relational Mapping (ORM) tool that simplifies database interactions. It provides a convenient way to work with database records through its built-in collections. While Laravel comes with a variety of pre-defined collection methods, you can also extend the basic Illuminate\Database\Eloquent\Collection class to simplify recordsets manipulation.

In this tutorial, we will explore how to create and use custom Laravel Eloquent collections, with practical examples to demonstrate their usefulness.

Understanding Laravel Eloquent Collections

Before diving into custom Eloquent collections, let’s briefly understand the concept of what they are. Eloquent collections are PHP arrays with additional helper methods that provide a convenient way to work with sets of Eloquent model records.

They offer a range of useful methods for filtering, mapping, sorting, and manipulating data.

Creating a Custom Eloquent Collection

To create a custom Eloquent collection, you need to extend the base Illuminate\Database\Eloquent\Collection class provided by Laravel. This base class provides several helper methods and features that can be leveraged when creating your custom collection.

use Illuminate\Database\Eloquent\Collection;
class CustomCollection extends Collection
{
    // Your custom collection methods goes here
}

To make your custom Eloquent collection more powerful, you can add your own methods. These methods can be specific to your application’s domain or offer additional convenience when working with collections.

This strategy can allows you to incapsulate certain logic in a single class that can be reused across the application.

Real life example of Custom Eloquent Collection

Let’s consider an example of a booking system where we want to resort the internal items according to specific characteristics, but it is much easier to do at code level instead than SQL.

namespace App\Collections;
use App\Models\Room;
use Illuminate\Database\Eloquent\Collection;
class AvailableRoomsCollection extends Collection
{
    public function __constructor($data)
    {
        $this->sortBy(function (Room $room) {
            // Apply sorting logic
        });
    }
}

Or you can add a specific method to be called externally.

namespace App\Collections;
use App\Models\Room;
use Illuminate\Support\Collection;
class AvailableRoomsCollection extends Collection
{
    public function sortByAvailability()
    {
        return $this->sortBy(function (Room $room) {
            // Apply sorting logic
        });
    }
}

Since your custom collection is automatically sorted when created, you can use it in one or more controllers with the convenience of having the sorting logic encapsulated in the collection itself:

namespace App\Http\Controllers;
use App\Collections\AvailableRoomsCollection;
use App\Models\Room;
use Illuminate\Http\Request;
class AvailabilityController
{
  public_function index(Request $request)
  {
    return new AvailableRoomsCollection(Room::filter($request->filter)->get());
  }
}

You can also implement the newCollection method directly in the Room model class to automatically get the custom colleciton instance as a query result:

use App\Collections\AvailableRoomsCollection;
use Illuminate\Database\Model;
class Room extends Model
{
    ...
    /**
     * Create a new Eloquent Collection instance.
     *
     * @param  array  $models
     * @return \Illuminate\Database\Eloquent\Collection
     */
    public function newCollection(array $models = []): AvailableRoomsCollection
    {
        return new AvailableRoomsCollection($models);
    }
    ...
}

You can simplify the Controller even more by returning the result of the query directly.

class AvailabilityController
{
    public_function index(Request $request)
    {
        return Room::filter($request->filter)->get();
    }
}

Custom Laravel Eloquent collections provide a way to extend the functionality of the default collection methods and add convenience methods and behaviours tailored to your application’s needs. By creating custom collections you can streamline your codebase.

Autofix your Laravel application for free

Inspector is a Code Execution Monitoring tool specifically designed for software developers. You don’t need to install anything on the infrastructure, just install the Laravel package and you are ready to go.

If you are looking for effective automation, and the ability to automatically receive code change proposals to fix application errors try Inspector for free. Register your account.

Or learn more on the website: https://inspector.dev

Related Posts

Laravel Http Client Overview and Monitoring

Laravel HTTP client was introduced starting from version 10 of the framework, and then also made available in all previous versions. It stands out as a powerful tool for making HTTP requests and handling responses from external services. This article will delve into the technical foundations of the Laravel HTTP client, its motivations, and how

Laravel Form Request and Data Validation Tutorial

In this article I will talk about Laravel Form Request to send data from your application frontend to the backend. In web applications, data is usually sent via HTML forms: the data entered by the user into the browser is sent to the server and stored in the database eventually. Laravel makes it extremely simple

Upload File in Laravel

You can upload file in Laravel using its beautiful unified API to interact with many different types of storage systems, from local disk to remote object storage like S3. As many other Laravel components you can interact with the application filesystem through the Storage Facade: Illuminate/Support/Facades/Storage This class allows you to access storage drivers called