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

ActiveBfg-app[Utility &amp; Helpers](/categories/utility)

bfg/transformer
===============

1.4.4(1y ago)062.6k1MITPHPPHP &gt;=8.0.0

Since Mar 24Pushed 1y ago2 watchersCompare

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

READMEChangelogDependencies (1)Versions (51)Used By (0)

Eloquent transformer
====================

[](#eloquent-transformer)

Install
-------

[](#install)

```
composer require bfg/transformer
```

Description
-----------

[](#description)

The package is designed to transform data `for` the model (on the example obtained by the data from the API). And data `from` the model (for example, when you need to send data back on the API).

Usage
-----

[](#usage)

### Create new transformer

[](#create-new-transformer)

```
php artisan make:transformer UserTransformer -m User
```

Describe all the fields that you will fill in the new class `App\Transformers\UserTransformer` in the `$toModel` variable:

```
use Bfg\Transformer\Transformer;
...
class UserTransformer extends Transformer
{
    /**
     * If your data that you received from
     * a third-party source have an Identifier,
     * then you need to specify this field.
     * @var string|null
     */
    protected ?string $remoteId = "ID";

    /**
     * An alternative source indicate the model
     * if it is not sent to the transformer.
     * @var string|null
     */
    protected ?string $modelClass = User::class;

    /**
     * Mapping to send data generation into the model.
     * @var string[]
     */
    protected array $toModel = [
        'FullName' => 'name',
        'Email' => 'email',

        // or if you identical key names:
        'name',
        'email',

        // for related iteration
        ContactsTransformer::class // The transformer of contacts
            => 'contacts', // The relation name in the model
    ];

    /**
     * Mapping for the direction of data generation
     * from the model, back to third-party service.
     * @var string[]
     */
    protected array $fromModel = [
        'name' => ['FirstName', 'LastName'],
        'address' => 'Address',
        'email' => 'Email',
        'phone' => 'Phone',
    ];

    /**
     * To implement the data unloading mechanism
     * on third-party service.
     * @return void
     */
    public function upload()
    {

    }
}
```

### Mutators

[](#mutators)

For fully transformation, it is often necessary to process a little more accurately, for this there are mutators in different directions:

```
use Bfg\Transformer\Transformer;
...
class UserTransformer extends Transformer
{
    ...
    protected array $toModel = [
        'FullName' => 'name',
        'Email' => 'email',
    ];

    protected array $fromModel = [
        'name' => ['FirstName', 'LastName'],
        'email' => 'Email',
    ];

    protected function toNameAttribute($dataValue)
    {
        $this->data; // All data is available on this property.
        $this->model; // The model is available on this property.

        return $dataValue;
    }

    protected function fromNameAttribute($modelValue)
    {
        return $modelValue;
    }

    protected function forFirstNameDataAttribute($modelValue)
    {
        return $modelValue;
    }

    protected function forLastNameDataAttribute($modelValue)
    {
        return $modelValue;
    }

    protected function forEmailDataAttribute($modelValue)
    {
        return $modelValue;
    }
}
```

### Casting

[](#casting)

All transformation casting rules are completely copied from the [casting of `Laravel Attributes`](https://laravel.com/docs/8.x/eloquent-mutators#attribute-casting)and their functionality is absolutely identical (except for the `set` of custom casts):

```
...
    protected $casts = [
        'views' => 'int'
    ];
...
```

> Applies to data, not to the model.

### Model catch

[](#model-catch)

In order to catch a model definition for a transformer (based on data), you can use the `getModel` method:

```
use Bfg\Transformer\Transformer;
use App\Models\User;
...
class UserTransformer extends Transformer
{
    ...
    protected function getModel()
    {
        return User::where('remote_id', $this->data['ID'])->first()
            ?: parent::getModel();
    }
}
```

### Data catch

[](#data-catch)

For a transformer, you can determine the value for processing directly inside, this mechanism allows you to generate built-in dependent nesting. According to the rules, if a collection `Illuminate\Support\Collection` is returned, then the selection of a transformer instance will be created for each entry.

```
use Bfg\Transformer\Transformer;
use App\Models\User;
...
/**
 * @property-read ApiService $api For example some "ApiService" class
 */
class UserTransformer extends Transformer
{
    ...
    protected function getData()
    {
        return $this->api->findUser($this->model->remote_id);
    }
}
```

### Data to model

[](#data-to-model)

```
use App\Transformers\UserTransformer;
...
$data = [
    'userName' => 'Thomas',
    'userEmail' => 'thomas@example.com',
]; // for example, any data

$model = UserTransformer::make()
    ->withData($data)
    ->toModel(); // Instance of User model

// Or from any model
$model = UserTransformer::make()
    ->withData($data)
    ->withModel(User::find(1))
    ->toModel(); // With my instance of User model

$model->save();
```

### Data from model

[](#data-from-model)

```
use App\Models\User;
use App\Transformers\UserTransformer;
...
$model = User::find(1);

$data = UserTransformer::make()->withModel($model)->toData()->data;
    // => ['userName' => 'Thomas','userEmail' => 'thomas@example.com']

// Or with you data filling
$fillData = (object) ['userName' => null, 'userEmail' => null, 'otherData' => 'test']
UserTransformer::make()->withModel($model)->withData($fillData)->toData()->upload();
```

Next, the collection perceives all the methods of the model to the entire collection:

```
use App\Transformers\TransformerCollection;
...
/** @var TransformerCollection $collection */
$collection->save();
```

To start the entire chain in the transaction:

```
use App\Transformers\TransformerCollection;
...
/** @var TransformerCollection $collection */
$collection->transaction()->save();
// For additional updating
$collection->transaction()->save()->update([
    'api_updated_at' => now()
]);
```

###  Health Score

37

—

LowBetter than 81% of packages

Maintenance33

Infrequent updates — may be unmaintained

Popularity23

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity67

Established project with proven stability

 Bus Factor1

Top contributor holds 100% 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 ~18 days

Recently: every ~168 days

Total

50

Last Release

663d ago

Major Versions

0.2.7 → 1.0.02022-04-13

### Community

Maintainers

![](https://www.gravatar.com/avatar/59b2d162a30938ac2c3c56340ebea07a6778a3e1c86cb70b5bc28b69a1c3f04d?d=identicon)[bfg](/maintainers/bfg)

---

Top Contributors

[![Xsaven](https://avatars.githubusercontent.com/u/1726771?v=4)](https://github.com/Xsaven "Xsaven (54 commits)")

---

Tags

laravelextensiontransformer

### Embed Badge

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

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

###  Alternatives

[psalm/plugin-laravel

Psalm plugin for Laravel

3355.3M346](/packages/psalm-plugin-laravel)[codewithdennis/filament-select-tree

The multi-level select field enables you to make single selections from a predefined list of options that are organized into multiple levels or depths.

329530.5k29](/packages/codewithdennis-filament-select-tree)[worksome/exchange

Check Exchange Rates for any currency in Laravel.

124603.0k](/packages/worksome-exchange)[tomshaw/electricgrid

A feature-rich Livewire package designed for projects that require dynamic, interactive data tables.

119.4k](/packages/tomshaw-electricgrid)[tarfin-labs/event-machine

Event-driven state machines for Laravel with event sourcing, type-safe context, and full audit trail.

199.4k](/packages/tarfin-labs-event-machine)[tapp/filament-form-builder

User facing form builder using Filament components

132.4k3](/packages/tapp-filament-form-builder)

PHPackages © 2026

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