1. Go to this page and download the library: Download logaretm/transformers 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/ */
logaretm / transformers example snippets
class UsersController extends Controller
{
public function index(UserTransformer $transformer)
{
$users = User::get();
return response()->json([
'users' => [
'data' => $transformer->transform($users)
]
]);
}
}
$transformer = new UserTransformer;
class User extends Model implements Transform
{
use TransformableTrait;
/**
* Defines the appropiate transformer for this model.
*
* @var
*/
protected $transformer = UserTransformer::class;
}
if(Transformer::canMake(User::class); // returns true if the transformer is registered.
$transformer = Transformer::make(User::class); // creates a transformer for the model.
$transformer = new UserTransformer();
$users = User::with('posts')->get();
$data = $transformer->with('posts')->transform($users);
$transformer = new UserTransformer();
$users = User::with('posts.tags')->get();
$data = $transformer->with('posts.tags')->transform($users);
$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.