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.

New to Inspector? Try it for free now

I hope this article can help you make better decisions for the design of your application.

Are you responsible for application development in your company? Consider trying my product Inspector to find out bugs and bottlenecks in your code automatically. Before your customers stumble onto the problem.

Inspector is usable by any IT leader who doesn’t need anything complicated. If you want effective automation, deep insights, and the ability to forward alerts and notifications into your messaging environment try Inspector for free. Register your account.

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

Related Posts

php-iterators-inspector

PHP Iterators for walking through data structures – FastTips

PHP Iterators are essential tools for efficiently traversing and manipulating data structures like arrays, objects, and more. They provide a clean and memory-efficient way to work with large datasets without loading the entire dataset into memory at once. In this tutorial, we will explore PHP iterators and how to use them for walking through various

Adoption of AWS Graviton ARM instances (and what results we’ve seen)

Working in software and cloud services you’ve probably already heard about the launch of new the Graviton machines based on custom ARM CPUs from AWS (Amazon Web Services).  In this article you can learn the fundamental differences between ARM and x86 architecture and the results we’ve achieved after the adoption of Graviton ARM machines in

Announcing increased data retention for monitoring data

Long story short: In the last 2 months of work we’ve achieved great results in cost optimization by refactoring both our infrastructure and code architecture, and we want to pass this value to you in the form of a longer data retention for your monitoring data. Thanks to these changes we are increasing our computational