Calling API resource's collection() method directly from the model in Laravel

If you return model's data in your API using an API resource (via collection() method), while observing the naming rules, you most likely have to import the namespace of the resource class and assign an alias to it via the as operator, because usually the resource name and model match.

I don't think it's very elegant way. I suggest you to implement the collection() method in models, which will find the needed resource and call the collection() method from it.

To do this, write a new trait Collectable:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
<?php   namespace App\Models\Concerns;   use Illuminate\Support\Collection;   trait Collectable { /** * Filter output model data via API resource class. * * @param Collection $collection * @return mixed */ public static function collection(Collection $collection) { $resourceClass = self::$resourceClass ?? class_basename(self::class);   return call_user_func( ["\\App\\Http\\Resources\\$resourceClass", 'collection'], $collection ); } }

All that remains is to connect this trait to your models, whose data you return in your API.

Now you don't need to access the resource class 😲


Spelling error report

The following text will be sent to our editors: