valeryq / dto by valeryq

Laravel array formatter similarity DTO
13
1
2
Package Data
Maintainer Username: valeryq
Maintainer Contact: valprogramm@gmail.com (Valery Zakharchenko)
Package Create Date: 2015-01-14
Package Last Update: 2015-01-15
Language: PHP
License: Unknown
Last Refreshed: 2024-06-24 15:12:34
Package Statistics
Total Downloads: 13
Monthly Downloads: 0
Daily Downloads: 0
Total Stars: 1
Total Watchers: 2
Total Forks: 0
Total Open Issues: 0

#Laravel array formatter similarity DTO#

Introduction

Laravel can serialize EloquentModel or EloquentCollection to array, but it can't get only certain data (for example: return JSON from controller). DTO can return to response only certain data large nested.

Installation

Require this package in your composer.json and update composer. This will download the package.

"valeryq/dto": "1.0.0"

After updating composer, add the ServiceProvider to the providers array in app/config/app.php

'Valeryq\DTO\DTOServiceProvider',

You can use the facade for shorter code. Add this to your aliases:

'DTO' => 'Valeryq\DTO\DTOFacade',

How it use

Eloquent model example:

class UserController extends \BaseController 
{
    public function getUser() 
    {
        $user = UserModel::find(1);

        return DTO::make($user)->only(['id', 'firstname']);

        or
     
        return DTO::make($user)->except(['lastname']);
    }   
}

Eloquent collection example:

class UserController extends \BaseController 
{
    public function getUser() 
    {
        $user = UserModel::where('firstname', 'Test')->get();

        return DTO::make($user)->only(['id', 'firstname']);

        or
     
        return DTO::make($user)->except(['lastname']);
    }   
}

Nested objects:

class UserController extends \BaseController 
{
    public function getUser() 
    {
        $user = UserModel::with('posts')->find(1);

        return DTO::make($user)->only(['id', 'firstname', 'posts.id', 'posts.body']);

        or
     
        return DTO::make($user)->except(['lastname', 'posts.body']);
    }   
}