1. Go to this page and download the library: Download erikgall/transformer library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
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);
}
}
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;
}
}
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();
}
}
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.