Laravel 5.* package to easily introduce a transformation layer for your data

Related tags

Laravel laraformer
Overview

Laraformer

Laraformer is a laravel 5.* package that lets you easily introduce a transformation layer for your data.

Laraformer (originated from Laravel Transformers) is a Laravel 5.* package that lets you easily introduce the transformer logic in your Laravel applications.

Features

  • Automatic transformation of the models. Also support for manual transformation
  • Lets you transform almost any kind of data i.e. arrays, objects, collections, paginated data etc
  • Not only you can transform models but also any dataset
  • Supports both Eloquent and Moloquent
  • Ease of use; for automatic transformation, you just need a transform function in your models and for manual, there is a single function call. More to it in a moment.
  • Lets you keep your transformation logic separate
  • Lets you make sure of the fact that any changes in schema doesn't affect the output

Two steps installation

All you have to do is install the package and add the service provider

  • Run composer require kamranahmedse/laraformer in the terminal

  • Add Service Provider Open config/app.php and add KamranAhmed\Laraformer\TransformerServiceProvder::class to the end of providers array:

    'providers' => array(
        ....
        KamranAhmed\Laraformer\TransformerServiceProvder::class,
    ),

How to use

The installation will automatically setup everything that is there to use the package. Lets get into the real stuff now, shall we?!

Transforming Models

Just add the transformation logic to a method called transform in your model and directly respond with model/collection of models/paginated model response.

You can transform your models in one of the two ways:

  • Automatic transformation of the response
  • Manually transform the response

Let me explain the usage with an example.

Example

Sample Table/Collection Lets say that we have a users table/collection with the associated model called User. The table/collection looks like following

Column Type Sample Data
id int 120
name string John Doe
profession string Engineer
design_options string (JSON for example) [{"theme_name": "larology", "fields":[{"type": "integer", "name": "some-dummy-field"}]}]
is_admin bool true
created_at datetime 2016-03-04

Required Output And here is the output we need

[
    {
        "public_id": "x72sl1",
        "name": "John Doe",
        "slug": "john-doe",
        "occupation": "Engineer",
        "is_admin": true,
        "joined_on": "2 days ago",
        "profile_design": [
            {
                "theme_name": "larology",
                "fields": [
                    {
                        "type": "integer",
                        "name": "some-dummy-field"
                    }
                ]
            }
        ]
    }
]

The Model In order to generate the above ouput, all you need to do is, add a transform method in your model i.e.

class User extends Eloquent 
{
    ...
    public function transform(User $user) {
        return [
            'public_id' => $this->amalgamate($user->id),
            'name' => $user->name,
            'slug' => str_slugify($user->name),
            'occupation' => $user->profession,
            'is_admin' => (bool) $user->is_admin,
            'joined_on' => DateHelper::humanize($user->created_at),
            'profile_design' => json_decode($user->design_options, true)
        ];
    }
}

a) Automatically transform the response

For the automatic transformation, all you have to do is return the models directly i.e. with the model object, collection of models or a paginated models in the response. For example, the controller may look like below:

class UserController extends Controller 
{
    ...
    // Works well with model object
    public function show($id) {
        return User::find($id);
    }
    ...
    // Or you can return the collection
    public function all() {
        return User::all();
    }
    ...
    // Also paginated data is gracefully handled
    public function paginate() {
        return User::paginate(10);
    }
}

b) Manual transformation

If you would like to transform your model data for internal use, you can also do it. For that, you can either do it using a provided facade called \KamranAhmed\Laraformer\Facades\Transformer by using an alias called Laraformer i.e.

// Use the registered alias
$user = User::find(120);
$transformedUser = Laraformer::transformModel($user);
// Do something with $transformedUser

Also note that you still have to specify the transform method in the model.

Transforming any Dataset

Not only models, but you can also use laraformer to transform any kind of dataset whether it some data from an external source, some dataset that you magically generated etc. In order to do that, you can do one of the following.

  • Pass an object of a transformer class having a transform method
  • Pass a callback function

For example:

// Transforming using callback function
return Laraformer::forceTransform($dataset, function ($item) {
    return [
        'name' => $item['name'],
        'slug' => str_slugify($item['name']),
        'occupation' => $item['profession'],
        'is_admin' => (bool) $item['is_admin'],
        'joined_on' => DateHelper::humanize($item['created_at']),
        'profile_design' => json_decode($item['design_options'], true)
    ];
})

// Transforming using Transformer class object
$userTransformer = new UserTransformer;
return Laraformer::forceTransform($dataset, $userTransformer)

Contributing

  • Feel free to add some new functionality, polish some existing functionality etc and open up a pull request explaining what you did.
  • Report any issues in the issues section
  • Also you can reach me directly at [email protected] with any feedback
You might also like...
A package to easily make use of SVG icons in your Laravel Blade views.
A package to easily make use of SVG icons in your Laravel Blade views.

Blade Icons A package to easily make use of SVG icons in your Laravel Blade views. Originally "Blade SVG" by Adam Wathan. Turn... !-- camera.svg --

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

Laravel Model UUIDs Introduction Huge thanks to Micheal Dyrynda, whose work inspired me to create this package based on laravel-model-nanoid but uses

A package to easily make use of Iconsax in your Laravel Blade views.
A package to easily make use of Iconsax in your Laravel Blade views.

Blade Iconsax A package to easily make use of Iconsax in your Laravel Blade views. This package contains 1.000 icons in 6 diferent styles, a total of

Easily validate data attributes through a remote request
Easily validate data attributes through a remote request

Laravel Remote Rule Easily validate data attributes through a remote request. This package allows you to define a subset of custom rules to validate a

Laravel 2-Step Verification is a package to add 2-Step user authentication to any Laravel project easily.
Laravel 2-Step Verification is a package to add 2-Step user authentication to any Laravel project easily.

Laravel 2-Step verification is a package to add 2-Step user authentication to any Laravel project easily. It is configurable and customizable. It uses notifications to send the user an email with a 4-digit verification code. Laravel 2-Step Authentication Verification for Laravel. Can be used in out the box with Laravel's authentication scaffolding or integrated into other projects.

Laravel-Mediable is a package for easily uploading and attaching media files to models with Laravel 5.

Laravel-Mediable Laravel-Mediable is a package for easily uploading and attaching media files to models with Laravel. Features Filesystem-driven appro

Laravel package to normalize your data before saving into the database.

This package helps you normalize your data in order to save them into the database. The Goal is to having separate classes that handle the data normalization, and thus can be tested independently.

A Laravel Wrapper for the CoinDCX API. Now easily connect and consume the CoinDCX Public API in your Laravel apps without any hassle.
A Laravel Wrapper for the CoinDCX API. Now easily connect and consume the CoinDCX Public API in your Laravel apps without any hassle.

This package provides a Laravel Wrapper for the CoinDCX API and allows you to easily communicate with it. Important Note This package is in early deve

Package to easily test crudable controllers for Laravel based API

Laravel Crudable Test This package is very usefull to easily test crudable controllers. Installation You can install package via composer. Add reposit

Releases(v1.0.0)
  • v1.0.0(Mar 4, 2016)

    The first release of the package. Has the support for:

    • Automatic transformation of the models. Also support for manual transformation
    • Lets you transform almost any kind of data i.e. arrays, objects, collections, paginated data etc
    • Not only you can transform models but also any dataset
    • Supports both Eloquent and Moloquent
    • Ease of use; for automatic transformation, you just need a transform function in your models and for manual, there is a single function call. More to it in a moment.
    • Lets you keep your transformation logic separate
    • Lets you make sure of the fact that any changes in schema doesn't affect the output
    Source code(tar.gz)
    Source code(zip)
Owner
Kamran Ahmed
Lover of all things web and opensource. Coding and writing stuff for humans™. Building roadmap.sh
Kamran Ahmed
Laravel 5 Repositories is used to abstract the data layer, making our application more flexible to maintain.

Laravel 5 Repositories is used to abstract the data layer, making our application more flexible to maintain.

Anderson Andrade 4k Jan 6, 2023
An abstraction layer to get data from array or a file with dot-notation

Alex Unruh - Config This library is based on the Laravel config concept. It values performance and was built on top of the library Dflydev Dot Access

Alexandre Odair 3 May 20, 2022
Smeify is a Stable Automated Solution for Airtime and Data businesses in Nigeria, this package helps you integrate smeify easily into your laravel application.

Smeify is a Stable Automated Solution for Airtime and Data businesses in Nigeria, this package helps you integrate smeify easily into your laravel application.

Ogundiran Adewale Charles 2 Jul 27, 2022
A simple artisanal command framework for creating service layer classes

Introdução Este projeto tem como objetivo fornecer alguns comandos adicionais à interface de linha de comando do Laravel para manipular a estrutura da

Eliezer Alves 15 Feb 2, 2022
Easily add a full Laravel blog (with built in admin panel and public views) to your laravel project with this simple package.

Webdevetc BlogEtc - Complete Laravel Blog Package Quickly add a blog with admin panel to your existing Laravel project. It has everything included (ro

WebDevEtc. 227 Dec 25, 2022
Laravel comments - This package enables to easily associate comments to any Eloquent model in your Laravel application

Laravel comments - This package enables to easily associate comments to any Eloquent model in your Laravel application

Rubik 4 May 12, 2022
A package to easily make use of Iconic icons in your Laravel Blade views.

Blade Iconic A package to easily make use of Iconic icons in your Laravel Blade views. For a full list of available icons see the SVG directory. Iconi

Malik Alleyne-Jones 17 Aug 25, 2022
A package to easily make use of Simple Icons in your Laravel Blade views.

Blade Simple Icons A package to easily make use of Simple Icons in your Laravel Blade views. For a full list of available icons see the SVG directory.

UB Labs 12 Jan 17, 2022
This package allows you to easily track your laravel jobs!

Trackable Jobs For Laravel This package allows you to track your laravel jobs! Using this package, you can easily persist the output and the status of

Mateus Junges 220 Dec 25, 2022
Zarinpal is a laravel package to easily use zarinpal.com payment services in your applications

پکیج اتصال به درگاه پرداخت زرین پال zarinpal.com برای اتصال به درگاه پرداخت اینترنتی زرین پال و استفاده از api های آن می توانید از این پکیج استفاده کن

Rahmat Waisi 4 Jan 26, 2022