Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5 - fractal transformers - Sending parameters to the transformer to narrow down response

Tags:

php

laravel

So I have a model called VIP that has a LOT of information associated with it. As such, when we go to the route vip/{id} I return most of that information. However, when I go to vips/{per-page} I don't want to return ALL the data because the API would slow down exponentially. Instead I would rather just return some of the more basic stuff.

In order to do so I have a Transformer that creates the basic response at the top and then goes into some of the more complicated associations below and then returns it all. I would LIKE to send the transformer a flag of some sort that returns only the basic response if true. However, I am using fractal and can't seem to figure out a way to be able to send this flag to the transformer.

VipsController@index :

   /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request, $perPage = 15)
    {
        $page = $request->input('page');
        $vip = Cache::tags(['vips'])->remember("vip.index.$perPage.$page", 60, function() use ($perPage){
            Log::info('getting data from the database');
            return $this->vip->paginate($perPage, ['*'], ['gender','status','local','jobClass','nonMember','initiationDate','pensioner']);
        });

        return $this->fractal->paginatedCollection($vip, new VipTransformer());
    }

VipTransformer@transform:

    public function transform(Vip $vip)
    {
        $response = [
            'id' => $vip->vip_id,
            'first_name' => isset($vip->first_name) ? $vip->first_name : '',
            'last_name' => isset($vip->last_name) ? $vip->last_name : '',
            'birth_date' => isset($vip->birth_date) ? $vip->birth_date : '',
            'deceased_date' => isset($vip->deceased_date) ? $vip->deceased_date : '',
            'divorced_date' => isset($vip->divorced_date) ? $vip->divorced_date : '',
            'marriage_date' => isset($vip->marriage_date) ? $vip->marriage_date : '',
            'initiation_date' => isset($vip->initiationDate->date_value) ? $vip->initiationDate->date_value : '0000-00-00',
            'gender' => isset($vip->gender->code_description) ? $vip->gender->code_description : '',
            'status' => isset($vip->status->code_description) ? $vip->status->code_description : '',
            'local' => isset($vip->local) ? "{$vip->local->local_code} - {$vip->local->local_name}" : '',
            'jobClass' => isset($vip->jobClass) ? $vip->jobClass->code_description : '',
            'nonMember' => isset($vip->nonMember) ? $vip->nonMember->code_description : '',
            'age' => isset($vip->birth_date) && $vip->birth_date !== '0000-00-00' ? Carbon::parse($vip->birth_date)->age : 0,
        ];

        // Grab retirement date from pension tables
        $response['retirement_date'] = $vip->pensioner->retirement_date ?? '0000-00-00';

        // Grab the associated information for the vip profile
        $reciprocals = [];
        $addresses = [];
        $phone_numbers = [];
        $emails = [];

        foreach($vip->addresses as $address) {
            $addresses = [
                'address1' => $address->address_1 ?? '',
                'address2' => $address->address_2 ?? '',
                'city' => $address->city ?? '',
                'zip' => $address->zip_code ?? '',
                'country' => $address->country->code ?? '',
                'state' => $address->state->state_province_code ?? '',
                'is_default' => $address->is_default ?? false,
            ];
        }

        // TODO: Add record status trait to each

        foreach ($vip->phones as $phone) {
            $phone_numbers[] = [
                'extension' => $phone->extension ?? '',
                'number' => $phone->phone_number ?? '',
                'is_default' => $phone->is_default ?? false,
            ];
        }

        foreach ($vip->emails as $email) {
            $emails[] = [
                'email_address' => $email->email_address ?? '',
                'is_default' => $email->is_default ?? false,
            ];
        }

        foreach ($vip->reciprocalMembers as $member) {
            $reciprocals[] = $member->effective_date . ' - ' . $member->fund->fund_abbreviation . ' - ' . $vip->local->local_name;
        }

        $response['addresses'] = $addresses;
        $response['phone_numbers'] = $phone_numbers;
        $response['emails'] = $emails;
        $response['reciprocals'] = $reciprocals;


        return $response;
    }

Is there a way for me to send a flag to the transformer using Fractal? Is there another better way maybe?

UPDATE:

The answer works but I did it this way....feel free to do as you wish:

Transformer:

protected $indexRequest;

public function __construct($indexRequest = null)
{
    $this->indexRequest = $indexRequest ?? false;
}

fractal call:

return $this->fractal->paginatedCollection($vips, new VipTransformer(true));

like image 308
Bill Garrison Avatar asked Dec 04 '15 16:12

Bill Garrison


1 Answers

I have never used fractal, but couldn't you do something like adding a flag on your VipTransformer class.

 <?php

class VipTransformer
{
    protected $basicResponseFlag = false;


    public function setFlag($flag)
    {
        $this->basicResponseFlag = $flag;

    }

    public function transform(Vip $vip)
    {
        if($this->basicResponseFlag){
            //do basic stuff
        }
    }
}

Now on your VipsController@index :

/**
 * Display a listing of the resource.
 *
 * @return \Illuminate\Http\Response
 */
public function index(Request $request, $perPage = 15)
{
    $page = $request->input('page');
    $vip = Cache::tags(['vips'])->remember("vip.index.$perPage.$page", 60, function() use ($perPage){
        Log::info('getting data from the database');
        return $this->vip->paginate($perPage, ['*'], ['gender','status','local','jobClass','nonMember','initiationDate','pensioner']);
    });

    $vipTransformer = new VipTransformer();
    $vipTransformer->setFlag(true); //set your transfomer to basic mode
    return $this->fractal->paginatedCollection($vip, $vipTransformer);
}
like image 175
Fabio Antunes Avatar answered Sep 30 '22 05:09

Fabio Antunes