Skip to content

Instantly share code, notes, and snippets.

@rizqidjamaluddin
Last active August 29, 2015 14:27
Show Gist options
  • Save rizqidjamaluddin/87bdc36beae1333f8104 to your computer and use it in GitHub Desktop.
Save rizqidjamaluddin/87bdc36beae1333f8104 to your computer and use it in GitHub Desktop.
Transformer Example
<?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!
];
}
}
@rizqidjamaluddin
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment