Search code examples
phplaraveleloquentlaravel-9laravel-resource

Filter a model before you create an resource Collection


I am looking for a way that my ProductResource Collection will only include products with active prices.

In my routes/api.php am using a Collection as so:

Route::get('/product', function (Request $request) {
  return new ProductCollection(
    Product::all()
  );
});

In the model App\Models\Product there is a relationship for prices

public function prices () {
  return $this->hasMany(ProductsPrice::class);
}

and in the App\Models\ProductsPrice there is a scopeIsActive that I want to call before my collection is created.

public function scopeIsActive($query)
{
  return $query->where('is_active', true);
}

Is there a way I can call this isActive scope without creating a Controller just to query the Products with a active price and put that in a ResourceCollection in the routes/api.php, like so?

Route::get('/product', function (Request $request) {
  return new ProductCollection(
    Product::all()->prices()->isActive()
  );
});

Solution

  • You can do like this.

    Route::get('/product', function (Request $request) {
      return new ProductCollection(
        Product::with(['prices' => function($query) {
            $query->isActive();
        }])->get()
      );
    });