Laravel Pass Parameter To Resource Collection

Laravel – Passing Parameter to Resource Collection

In Laravel, Resource Collections allow you to transform a collection of models into a JSON response. Sometimes, you may need to pass additional parameters to the resource collection to customize the data being returned. Here’s how you can achieve that:

Step 1: Create a Resource Collection

To pass parameters to a resource collection, you need to first create a resource collection class. This class extends the Illuminate\Http\Resources\Json\ResourceCollection class.


  namespace App\Http\Resources;

  use Illuminate\Http\Resources\Json\ResourceCollection;

  class YourResourceCollection extends ResourceCollection
  {
      private $customParam;

      public function __construct($resource, $customParam)
      {
          parent::__construct($resource);
          $this->customParam = $customParam;
      }

      public function toArray($request)
      {
          return [
              'data' => $this->collection,
              'custom_param' => $this->customParam,
          ];
      }
  }
  

Step 2: Use the Resource Collection

Now, you can use the resource collection in your controllers or routes.


  use App\Http\Resources\YourResourceCollection;
  use App\Models\YourModel;

  $customParam = 'Your custom parameter';

  // Fetch the data from the database
  $models = YourModel::all();

  // Pass the custom parameter to the resource collection
  $resourceCollection = new YourResourceCollection($models, $customParam);

  // Return the resource collection as the JSON response
  return $resourceCollection;
  

Step 3: Output

The JSON response will include the data from the models as well as the custom parameter you passed:


  {
      "data": [
          // Your transformed resource data here
      ],
      "custom_param": "Your custom parameter"
  }
  

That’s it! You have now successfully passed a custom parameter to a Laravel resource collection.

Read more

Leave a comment