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.

You can follow me on Linkedin or X. I post about building my SaaS business.

Monitor 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.

Inspector is super easy to use and require zero configurations.

If you are looking for HTTP monitoring, query insights, and the ability to forward alerts and notifications into your preferred messaging environment try Inspector for free. Register your account.

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

Related Posts

The Neuron Facade: Talking to Your AI Agent in Laravel

Before this release, using Neuron AI inside Laravel meant creating a dedicated agent class, extending Agent, implementing a provider() method, and wiring the system prompt yourself. That pattern is the right one once your agent has a personality, a set of tools, and a role in your application. But it is a lot of ceremony

LLM Provider Fallback in PHP: Automatic Failover in Neuron AI Router

When I published the first article about the Neuron AI Router, I expected questions about routing rules. Which rule to use for structured output, how to write a custom one, how the round robin behaves under load. Some of those questions arrived, but the most frequent one was different, and it wasn’t really about routing