Ad

Transformer Usage On Laravel/dingo API

- 1 answer

I am creating a set of REST APIs to be exposed to my mobile apps using laravel repository pattern.I am using dingo as the REST framework.I am confused on how the response for the APIs should be done using a transformer.

I have the below controller function

if(!$user) { 
    //Authenticate with Twitter and authenticate
    //Register user and issue jwt
    $user = Sentinel::register($device_details);
    $user_data = json_decode($user,true);
    $device_details['users_id'] = $user['users_id'] = $user_data['id'];
    $this->device_details->create($device_details);             
}
$token = JWTAuth::fromUser($user);
$user_array = $user->toArray();
$user_array['token'] = $token;   //An array containing user details and token
return $this->response->item($user_array, new UserTransformer)->setStatusCode(200);   //I can only pass an object (eloquent) as the #1 parameter

My Tranformer class

namespace App\Api\V1\Transformers;

use App\User;
use League\Fractal\TransformerAbstract;

class UserTransformer extends TransformerAbstract {

    public function transform(User $user)
    {
        return [
            'users_id'     => (int) $user->users_id,
            'AUTH-TOKEN'   => $user->token // Doesnt comes from database,
...
        ];
    }
}

Now my question is,

  1. I can only use eloquent objects with a tranformer?
  2. Here in this case, the token is generated by jwt library and I binded it with the array as a single user array. Now how will be able to pass this array to a presenter.
  3. The documention for fractal transformer doesn't say about passing array to the presenter.My data might not always comes from an eloquent object.
  4. How do I handle this case?
  5. Why are presenters used? I would either use a presenter or a tranformer right?
Ad

Answer

I have check your code, Please check below code that might work for you. You have to pass $user without converting to array :

if(!$user) { 
             //Authenticate with Twitter and authenticate
            //Register user and issue jwt
            $user = Sentinel::register($device_details);
            $user_data = json_decode($user,true);
            $device_details['users_id'] = $user['users_id'] = $user_data['id'];
            $this->device_details->create($device_details);             
           }
   $token = JWTAuth::fromUser($user);
   $user_array = $user->toArray();
   $user_array['token'] = $token;   //An array containing user details and token
    $user->token = $token;
   return $this->response->item(UserTransformer::transform($user))->setStatusCode(200);   //I can only pass an object (eloquent) as the #1 parameter
Ad
source: stackoverflow.com
Ad