Search code examples
phplaraveleloquenttransformer-model

How to pass all Eloquent (ORM) results throught a Laravel dataTransformer?


I getting results from a query built using Eloquent (Laravel's ORM)

$query = Lawyer::whereHas('user', function($q) use ($request) {
            $q->where('is_active', true);
        });
$result = $query->get()

I would like to pass the results I get throught a trasformer class LawyerTransformer extends TransformerAbstract{} to add some data to the results.

When I try this :

$this->collection($query->get(), new LawyerTransformer())

I have the following issue : Method [collection] does not exist.

How can I transform all the results using a transformer ?


Solution

  • You could use the transform method on the collection instance to achieve something like that here is an example that will increment all values in an array by 1;

    $collection = collect([1, 2, 3]);
    
    $collection->transform(function ($item, $key) {
        return (new IncrementTransformer)->transform($item);
    });
    

    And the transfomer class

    class IncrementTransformer
    {
        public function transform($item)
        {
            return $item += 1;
        }
    }
    

    You could probably write this a little cleaner but you get the basic idea.