Skip to content

Instantly share code, notes, and snippets.

@davidhemphill
Last active September 7, 2016 19:44
Show Gist options
  • Save davidhemphill/d8d55d4132624ce7e6d31145132089b2 to your computer and use it in GitHub Desktop.
Save davidhemphill/d8d55d4132624ce7e6d31145132089b2 to your computer and use it in GitHub Desktop.
<?
public function show($id)
{
return User::findOrFail($id)
->present(ApiPresenter::class);
}
<?
public function index()
{
return response()->json([
User::all()
->present(ApiPresenter::class)
->map(function ($user) {
return [
'first_name' => $user->first_name,
'last_name' => $user->last_name,
'name' => $user->fullName(),
'role' => $user->role(),
'signup_date' => $user->createdAt(),
'active' => $user->isActive(),
];
})
]);
}
<?php
namespace App\Users\Presenters;
class ApiPresenter
{
/**
* This gets serialized in the JSON
*/
public function getFullNameAttribute()
{
return $this->fullName();
}
public function fullName()
{
return trim($this->model->full_name . ' ' . $this->model->last_name);
}
public function createdAt()
{
return $this->model->created_at->format('n/j/Y');
}
public function isActive()
{
return (bool) $this->model->is_active;
}
public function role()
{
if ($this->model->is_admin) {
return 'Admin';
}
return 'User';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment