PHPackages                             logaretm/transformers - 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. [Utility &amp; Helpers](/categories/utility)
4. /
5. logaretm/transformers

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

logaretm/transformers
=====================

Simple laravel eloquent models transformers.

0.2.5(9y ago)2028.3k3[2 issues](https://github.com/logaretm/transformers/issues)MITPHP

Since Feb 20Pushed 9y ago4 watchersCompare

[ Source](https://github.com/logaretm/transformers)[ Packagist](https://packagist.org/packages/logaretm/transformers)[ RSS](/packages/logaretm-transformers/feed)WikiDiscussions master Synced today

READMEChangelog (1)Dependencies (7)Versions (11)Used By (0)

Transformers
============

[](#transformers)

[![Codacy Badge](https://camo.githubusercontent.com/25cb0475d4d592ea066cdad65ea6b1b37d37f801f0d4c4cc391b250cdc380dff/68747470733a2f2f6170692e636f646163792e636f6d2f70726f6a6563742f62616467652f47726164652f6464636131353537613030353435643438633632663163356336313663393834)](https://www.codacy.com/app/logaretm1/transformers?utm_source=github.com&utm_medium=referral&utm_content=logaretm/transformers&utm_campaign=Badge_Grade)[![Build Status](https://camo.githubusercontent.com/4a09b19e6e6306e1528bc80e4d272c783576ceec844a828aa225771054f8fec3/68747470733a2f2f7472617669732d63692e6f72672f6c6f67617265746d2f7472616e73666f726d6572732e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/logaretm/transformers)

This a package that provides transformer (reducer/serializer) classes and traits for the Laravel eloquent models.

Install
-------

[](#install)

Via Composer

```
composer require logaretm/transformers
```

##### Transformer:

[](#transformer)

A class responsible for transforming or reducing an object from one form to another then consumed.

##### Why would you use them?

[](#why-would-you-use-them)

Transformers are useful in API responses, where you want the ajax results to be in a specific form, by hiding attributes, exposing additional ones, or convert attribute types.

Also by delegating the responsibility of transforming models to a separate class make it easier to handle and maintain down the line.

##### Inspiration

[](#inspiration)

Having seen[Jeffery Way's Laracasts video](https://laracasts.com/series/incremental-api-development/episodes/4) and reading the book [Building APIs You Won't Hate](https://apisyouwonthate.com/), I wanted to create a simple package specific to laravel apps and because I needed this functionality in almost every project.

Usage
-----

[](#usage)

First you need to a transformer for your model. the transformer should extend the Transformer abstract class. And provide an implementation for the `getTransformation()` method.

```
class UserTransformer extends Transformer
{
    /**
     * @param $user
     * @return mixed
     */
    public function getTransformation($user)
    {
        return [
            'name' => $user->name,
            'email' => $user->email,
            'memberSince' => $user->created_at->timestamp
        ];
    }
}
```

Now you can use the transformer in multiple ways, inject it in your controller method and laravel IoC should instantiate it.

```
class UsersController extends Controller
{
    public function index(UserTransformer $transformer)
    {
        $users = User::get();

        return response()->json([
            'users' => [
                'data' => $transformer->transform($users)
            ]
        ]);
    }
}
```

You can also instantiate it manually if you don't think DI is your thing.

```
$transformer = new UserTransformer;
```

#### Dynamic Transformation

[](#dynamic-transformation)

You can also use the `TransformableTrait` on your model and define a `$transformer` property to be able to use the `getTransformer()` method.

```
class User extends Model implements Transform
{
    use TransformableTrait;

    /**
     * Defines the appropiate transformer for this model.
     *
     * @var
     */
    protected $transformer = UserTransformer::class;
}
```

then you can get the transformer instance using:

```
$user = User::first();
$transformer = $user->getTransformer(); // returns instance of UserTransformer.
```

which can be helpful if you want to dynamically transform models. but note that it will throw a `TransformerException` if the returned instance isn't an instance of `Transformer`.

#### Service Provider

[](#service-provider)

You may find retrieving the transformer over and over isn't intuitive, you can use the `TransformerServiceProvider` and a config file to define an array mapping each model or any class to a transformer class.

- Add this line to `config/app.php` in the service providers array.

`Logaretm\Transformers\Providers\TransformerServiceProvider::class`

- Run this artisan command:

`php artisan vendor:publish --provider="Logaretm\Transformers\Providers\TransformerServiceProvider" --tags="config"`

- Head over to config/transformers.php and populate the array with your model/transformer pairs.

```
    'transformers' => [
        User::class => UserTransformerClass
    ]
```

- Now you don't need to provide the `$transformer` property anymore on your model, nor implement the interface.

Note that the transformer resolution for the related model will prioritize the registered transformers.

Furthermore you can now use the static methods `Transformer::make` and `Transformer::canMake` to instantiate transformers for the models, using the trait is still helpful, but not required anymore.

```
if(Transformer::canMake(User::class); // returns true if the transformer is registered.
$transformer = Transformer::make(User::class); // creates a transformer for the model.
```

#### Relations

[](#relations)

It is also possible to transform a model along with their related models using the fluent method `with()`.

The related model transformer is resolved when:

- If the service provider is registered, then it will be resolved from the config array.
- If the model implements the `Transformable` contract which is automated by the `TransformableTrait`. it also needs to define the `$transformer` property.

otherwise the model will be transformed using a simple `toArray()` call.

```
$transformer = new UserTransformer();
$users = User::with('posts')->get();
$data = $transformer->with('posts')->transform($users);
```

you can also transform nested relations with the same syntax.

```
$transformer = new UserTransformer();
$users = User::with('posts.tags')->get();
$data = $transformer->with('posts.tags')->transform($users);
```

you can reset the transformer relations using `$transformer->resetRelations()` which will remove the related models from the transformation. also note that any call to `with` will reset the transformer automatically.

aside from collections you can transform a paginator, or a single object.

```
$users = User::get();
$transformer->transform($users); // returns an array of arrays.

$paginator = User::paginate(15);
$transformer->transform($paginator); // returns an array(15).

$user = User::first();
$transformedUser =  $transformer->transform($user); // returns a single array.
```

#### Alternate Transformations

[](#alternate-transformations)

You don't have to use only one transformation per transformer, for example you may need specific transformations for specific scenarios for the same model.

using the method `setTransformation` you can override the transformation method to use another one you have defined on the transformer.

```
class UserTransformer extends Transformer
{
    /**
     * @param $user
     * @return mixed
     */
    public function getTransformation($user)
    {
        return [
            'name' => $user->name,
            'email' => $user->email,
            'memberSince' => $user->created_at->timestamp
        ];
    }

    // Custom/Alternate transformation.
    public function adminTransformation($user)
    {
        return [
            'name' => $user->name,
            'email' => $user->email,
            'memberSince' => $user->created_at->timestamp,
            'isAdmin' => $user->isAdmin()
        ];
    }
}
```

To use the alternate transformation:

```
$transformer->setTransformation('admin');
```

or you can pass a closure as an alternate transformation method.

```
$transformer->setTransformation(function ($user) {
    return [
        'name' => $user->name,
        'email' => $user->email,
        'memberSince' => $user->created_at->timestamp,
        'isAdmin' => $user->isAdmin()
    ];
});
```

Note that the naming convention for the transformation method is `{transformation_name}Transformation`.

any subsequent calls to `transform` method will use that transformation instead.

Note that it will throw a TransformerException if the requested transformation does not exist.

to reset the transformation method use the `resetTransformation` method.

```
$transformer->resetTransformation(); //resets the transformation method.
```

or if you want to reset both relations and transformation method:

```
$transformer->reset(); //resets the transformation method and the relations.
```

#### Generating Transformers

[](#generating-transformers)

You can easily generate a transformer class using this artisan command:

```
php artisan make:transformer {transformer name}
```

which will create a basic transformer class in `app/Transformers` directory, don't forget to put your transformations there.

Testing
-------

[](#testing)

Use php unit for testing.

```
phpunit
```

TODO
----

[](#todo)

- Improve the API and method names.
- Maybe a console command to generate a transformer for a model.
- Use closures to override transformation.
- Write more todos.

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

[](#contributing)

All contributes will be fully credited.

Issues
------

[](#issues)

If you discover any issues, email me at  or use the issue tracker.

Credits
-------

[](#credits)

- [Abdelrahman Awad](https://github.com/logaretm)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

34

—

LowBetter than 75% of packages

Maintenance18

Infrequent updates — may be unmaintained

Popularity35

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity59

Maturing project, gaining track record

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 ~30 days

Recently: every ~39 days

Total

10

Last Release

3518d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/a926ff0583ce8945ecf1ae1a4b91c85cbdcca5675f269d7dcb422ac936a5f68e?d=identicon)[logaretm](/maintainers/logaretm)

---

Tags

laraveltransformers

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/logaretm-transformers/health.svg)

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

###  Alternatives

[laravel/sail

Docker files for running a basic Laravel application.

1.9k205.7M1.3k](/packages/laravel-sail)[laravel/ai

The official AI SDK for Laravel.

1.0k3.2M194](/packages/laravel-ai)[livewire/flux

The official UI component library for Livewire.

9527.8M128](/packages/livewire-flux)[laravel/mcp

Rapidly build MCP servers for your Laravel applications.

77022.3M150](/packages/laravel-mcp)[propaganistas/laravel-disposable-email

Disposable email validator

6023.0M7](/packages/propaganistas-laravel-disposable-email)[psalm/plugin-laravel

Psalm plugin for Laravel

3355.3M346](/packages/psalm-plugin-laravel)

PHPackages © 2026

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