PHPackages                             arifseft/transformer - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. arifseft/transformer

ActiveLibrary[Database &amp; ORM](/categories/database)

arifseft/transformer
====================

Laravel model transformers with relationships for API based applications.

v1.1.2(5y ago)074MITPHP

Since Jul 5Pushed 5y agoCompare

[ Source](https://github.com/arifseft/transformer)[ Packagist](https://packagist.org/packages/arifseft/transformer)[ Docs](https://github.com/erikgall/transformer)[ RSS](/packages/arifseft-transformer/feed)WikiDiscussions master Synced 5d ago

READMEChangelog (1)Dependencies (3)Versions (6)Used By (0)

Laravel Model Transformer
=========================

[](#laravel-model-transformer)

Transform Laravel Eloquent models into an array of specified keys with the option of including nested relationships as their transformed model array.

The Reason
----------

[](#the-reason)

This package was created to ease complexity, simplify model's, while allowing for them to be quickly transposed into an array of specified keys.

But turning an eloquent model into an array is easy right? You only have to call the `toArray()` method. The shortfall comes when you want the final array to only have specific fields/keys, as well as a nested relationship. You end up transforming the model inside of your controller, specifying each and every key and value the array should have.

### Example

[](#example)

#### Without Laravel Model Transformer

[](#without-laravel-model-transformer)

```
$user = App\User::with('school')->first();

$data = $user->toArray();

/**
 * What we get from the broad example is something like:
 *   [
 *      'id' => 1,
 *       'email' => 'example@example.com',
 *       'password' => '.....',
 *       'first_name' => 'John',
 *       'last_name' => 'Doe',
 *       'school_id' => 1,
 *       'created_at' => '...',
 *       'updated_at' => '...',
 *       'school' => [
 *           'id' => 1,
 *           'name' => 'Example University',
 *           'book_price' => 6000,
 *           'created_at' => '...',
 *           'updated_at' => '...'
 *       ]
 *   ];
 */
```

#### With Laravel Model Transformer

[](#with-laravel-model-transformer)

```
$user = App\User::first();
$user->transformer()->with('school')->transform();
```

And it returns:

```
[
    'id' => 1,
    'email' => 'example@example.com',
    'name' => 'John Doe',
    'school' => [
        'id' => 1,
        'name' => 'Example University'
    ]
]
```

Getting Started
---------------

[](#getting-started)

These instructions will get you get you up and running and using the package inside of your Laravel application.

### Prerequisities

[](#prerequisities)

The package was developed using Laravel 5.2 and PHP 7 so there may be incompatibilities with PHP 5.

```
- PHP >= 7
- Laravel >= 5.2

```

### Installing

[](#installing)

To install the package inside of your Laravel app, please follow the steps below.

Step 1: Run the following command from your project root.

```
composer require erikgall/transformer

```

Step 2: Add the package's service provider to your provider's array in you `app.php` config file.

```
EGALL\Transformer\TransformerServiceProvider::class

```

Step 3: Create a transformers directory inside of the directory where your model files live. Example using the location of a User model and its transformer class:

```
- app/User.php -> app/transformers/UserTransformer.php
- app/Models/User.php -> app/models/transformers/UserTransformer.php

* The Transformers directory must be in the same directory as you models... Only if you wish to use the automatic transformer class finder. Otherwise you must specify the model's transformer class/full namespace.

```

Step 4: Any models use wish to use a transformer with must implement the `EGALL\Transformer\Contracts\Transformable` interface/contract. You should also include the trait `EGALL\Transformer\Traits\TransformableModel` inside of your model classes.

```
namespace App;

use App\Transformers\UserTransformer;
use Illuminate\Database\Eloquent\Model;
use EGALL\Transformer\Contracts\Transformable;
use EGALL\Transformer\Traits\TransformableModel;

class User extends Model implements Transformable {

    use TransformableModel;

    // Only use if your Transformer directory does not sit in the same directory
    // as the model file.
    // protected $transformer = 'Acme\Transformers\UserTransformer';

    // Used in example below
    public function school()
    {

        return $this->belongsTo(School::class);

    }

}
```

Example below:

**User Model Transformer Class**

```
namespace App\Transformers;

use EGALL\Transformer\Transformer;

class UserTransformer extends Transformer {

    protected $keys = ['id', 'name', 'address'];

    // Create a custom attribute getter method like you would
    // in an eloquent model using the syntax get`AttributeName`Attrbute.
    public function getNameAttribute()
    {

        return $this->model->first_name . ' ' . $this->model->last_name;

    }

}
```

### Using the User Model Transformer from a controller.

[](#using-the-user-model-transformer-from-a-controller)

```
namespace App\Http\Controllers;

use Guard;

class UserController extends Controller {

    protected $user;

    public function __construct(Guard $guard)
    {

        $this->user = $guard->user();

    }

    public function me()
    {

        // Get only the user transformer data
        $data = $this->user->transform();

        // return an array with a transformed relationship.
        // if the relationship does not implement the transformable class
        // the transformer will call the toArray() on the model.
        $data = $this->user->transformer()->with('course')->transform();

    }

    public function dependencyInjectionExample(\EGALL\Transformer\Contracts\CollectionTransfomer $transformer)
    {

        // Collection example
        $transformer->collection(User::all())->keys('id', 'name')->with('school')->transform();

    }

    public function diExampleTwo(\EGALL\Transformer\Contracts\Transformer $transformer)
    {

        return $transformer->item($this->user)->keys(['id', 'first_name', 'last_name])->transform();

    }

}
```

Running the tests
-----------------

[](#running-the-tests)

Install the package and install it's dependencies. After, that is complete and once inside the package's root, run the following command:

```
vendor/bin/phpunit

```

Built With/Using
----------------

[](#built-withusing)

- Laravel
- PHPUnit
- PhpStorm

Contributing
------------

[](#contributing)

Please read [CONTRIBUTING.md](CONTRIBUTING.md) for details on our code of conduct, and the process for submitting pull requests to us.

Versioning
----------

[](#versioning)

We use [SemVer](http://semver.org/) for versioning. For the versions available, see the [tags on this repository](https://github.com/erikgall/transformer/tags).

Authors
-------

[](#authors)

- **Erik Galloway** - [Flip Learning](https://github.com/erikgall)

License
-------

[](#license)

This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details

###  Health Score

29

—

LowBetter than 59% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity9

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity67

Established project with proven stability

 Bus Factor1

Top contributor holds 66.7% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~368 days

Total

5

Last Release

2129d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/1f27f3ebb2dd83a12ddf5bc0a41b0f74ec60568c4d8229dfb09955ac76213321?d=identicon)[arifseft](/maintainers/arifseft)

---

Top Contributors

[![erikgall](https://avatars.githubusercontent.com/u/8866568?v=4)](https://github.com/erikgall "erikgall (2 commits)")[![arifseft](https://avatars.githubusercontent.com/u/5783078?v=4)](https://github.com/arifseft "arifseft (1 commits)")

---

Tags

jsonapilaravelmodeleloquenttransformer

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/arifseft-transformer/health.svg)

```
[![Health](https://phpackages.com/badges/arifseft-transformer/health.svg)](https://phpackages.com/packages/arifseft-transformer)
```

###  Alternatives

[mongodb/laravel-mongodb

A MongoDB based Eloquent model and Query builder for Laravel

7.1k7.2M71](/packages/mongodb-laravel-mongodb)[tucker-eric/eloquentfilter

An Eloquent way to filter Eloquent Models

1.8k4.8M26](/packages/tucker-eric-eloquentfilter)[dyrynda/laravel-model-uuid

This package allows you to easily work with UUIDs in your Laravel models.

4802.8M8](/packages/dyrynda-laravel-model-uuid)[spiritix/lada-cache

A Redis based, automated and scalable database caching layer for Laravel

591444.8k2](/packages/spiritix-lada-cache)[pdphilip/elasticsearch

An Elasticsearch implementation of Laravel's Eloquent ORM

145360.2k4](/packages/pdphilip-elasticsearch)[jedrzej/searchable

Searchable trait for Laravel's Eloquent models - filter your models using request parameters

127259.1k5](/packages/jedrzej-searchable)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
