Last active
August 29, 2015 14:27
-
-
Save rizqidjamaluddin/87bdc36beae1333f8104 to your computer and use it in GitHub Desktop.
Transformer Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class UserTransformer { | |
public function transform(User $user) { | |
// transformers are handy for... | |
return [ | |
'name' => $user->name, // just showing data | |
'age' => $user->age . ' years', // appending a word at the end | |
'avatar' => url('/avatars/'.$user->avatar), // formulating a URL | |
'active' => $user->posts()->count() > 0, // simple logic | |
'is_admin' => $user->hasGroup('admin'), // convenience flags | |
'friends' => $user->friends()->lists('name'), // quick lists | |
'join_date' => $user | |
->created_at->format('jS F Y'), // formatting | |
'member_duration' => $user | |
->created_at->diffForHumans(), // formatting for special situations | |
'referral' => $user->referral ? | |
$this->transform($user->referral) : false, // chain transformers! | |
]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Need to append extra information to a model before passing it to a view or JSON? Stop wrangling with eager loads, $appends, accessors and other shenanigans in a model. Build a transformer class, let it set up your data for you, and pass this instead.
Lens flare explosions not included.