How to filter a laravel collection with where clause on date values?

51 Views Asked by At

I have a periods table that has:

a start column of type date

an end column of type date

a current column of type boolean (only one period has this current column set to 1)

Then I have an events table with a date column of type date

In a controller I want to get a collection of events whose date column is between the start and the end of the current period i.e. the period with 1 in column current.

I do this

 $period=Period::where('current',1)->get();
 $start=$period[0]->start;
 $end=$period[0]->end;
 $events=EventResource::collection(Event::whereDate('date','>=',$start)->whereDate('date','<=',$end))->get();
 

The last line make the controller crash with this message.

"message": "Call to undefined method Illuminate\Database\Eloquent\Builder::mapInto()", "exception": "BadMethodCallException",

Whatis wrong here? I also tried where instead of whereDate the result is the same.

1

There are 1 best solutions below

0
Karl Hill On BEST ANSWER

You're trying to apply the get() method on a resource collection. The get() method is used to execute the query and get the results from the database, but you're trying to use it after transforming your results into a resource collection.

$period = Period::where('current', 1)->first();
$start = $period->start;
$end = $period->end;
$events = Event::whereDate('date', '>=', $start)->whereDate('date', '<=', $end)->get();
$eventsResource = EventResource::collection($events);