Farshad
Farshad

Reputation: 2000

How to customize api with resource on collection

I have a collection on my controller as below :

 $data = Accommodation::with(['city','accommodationRoomsLimited.roomPricingHistorySearch' => function($query) use($from_date,$to_date){
    $query->whereDate('from_date', '<=', $from_date);
    $query->whereDate('to_date', '>=', $to_date);
    }])    
    ->get();
 return new FilterResource($data);

and here is my filter resource

  public function toArray($request)
    {
    //return parent::toArray($request);
        return [
            'id'           => $this->id,
            'costumfields' => 'somecostumfields'
        ];
    }

Now I want to customize my resource so that I can add some custom fields to it and customize the current fields on the api but this code gives me the error below :

"message": "Property [id] does not exist on this collection instance.",

Upvotes: 0

Views: 338

Answers (2)

Udara Chathuranga
Udara Chathuranga

Reputation: 151

In Laravel Eloquent get() functions returns a collection.

Soulutions

  1. If you want to return all the accommodation as an array, you need to call collection() on the resource.
return FilterResource::collection($data);
  1. If you want to get one Accommodation, you need to call first() on the Eloquent query.
$accommodation = Accommodation::with([
    'city',
    'accommodationRoomsLimited.roomPricingHistorySearch' => function($query) use($from_date,$to_date) {
        $query->whereDate('from_date', '<=', $from_date);
        $query->whereDate('to_date', '>=', $to_date);
    }])    
    ->first();

 return new FilterResource($accommodation);

Upvotes: 3

Dino Numić
Dino Numić

Reputation: 1462

If you are returning a collection it should be:

return FilterResource::collection($data);

Upvotes: 3

Related Questions