dingo / api

A RESTful API package for the Laravel and Lumen frameworks.
BSD 3-Clause "New" or "Revised" License
9.33k stars 1.25k forks source link

How to add custom field in transformer based on outside variables? #1577

Closed imageslr closed 6 years ago

imageslr commented 6 years ago
Q A
Bug? no
New Feature? no
Framework Laravel
Framework version 5.x.y
Package version 1.x.y
PHP version 7.x.y

Dear all, excuse for my poor English.

I am a starter of this framework. Now I have question: how to add custom field in transformer based on outside variables?

To be specific, when fetching /users/:id, I want to add a following field in the response JSON to show that whether current user is follow the fetched user.

Now I'm doing it like this:

$currentUser = getLoggerdUserByRequest($request);
$user = User::find($id);
$user->following = $user->isFollowing($currentUser);
return $this->response->json($user);

I want to know is there someway I can pass extra variables to transformer? Currently I can only set TransformerClass like this:

class UserTransformer extends TransformerAbstract
{
    public function transform(User $user)
    {
        return [
            'id' => $user->id,
            //...
            'following' => (boolean)$user->following,
            'created_at' => $user->created_at->toDateTimeString()
        ];
    }
}

And I hope I can set following like this, just inside the UserTransformer:

class UserTransformer extends TransformerAbstract
{
    public function transform(User $user, User $currentUser)
    {
        return [
            'id' => $user->id,
            //...
            'following' => $user->isFollowing($currentUser),
            'created_at' => $user->created_at->toDateTimeString()
        ];
    }
}

Is there some better way to implement? Thank you!

gazben commented 6 years ago

@imageslr

  1. You can set fields of any eloquent model and pass it to the transformer as a collection
  2. You can inject Services to the transformer and make the computation there (not preferred)

The main idea here, is that you pass everything to the transformer and the transformer just returns the right data.

imageslr commented 6 years ago

Thank you! I am now using the first method, and I will look the second one. Thank you again!