Tucker-Eric / EloquentFilter

An Eloquent Way To Filter Laravel Models And Their Relationships
http://tucker-eric.github.io/EloquentFilter
MIT License
1.72k stars 120 forks source link

Can't sort on date #186

Closed xYvanB closed 1 year ago

xYvanB commented 1 year ago

In my trainsTrip model i've declared the following function

    public function frameDepartureDate($query,$startDate, $endDate)
    {
        return $query->where('full_departure_date', '>=', $startDate)->where('full_departure_date', '<=', $endDate);
    }

on my trainsTripFramesFilter

    public function frameDepartureDate($dateType, $startDate, $endDate, $query)
    {
        switch ($dateType) {
            case 1: //departure date
                $formattedStartDate = Carbon::createFromFormat('d/m/Y', $startDate);
                $formattedEndDate = Carbon::createFromFormat('d/m/Y', $endDate);
                return $query->frameDepartureDate($query, $formattedStartDate, $formattedEndDate);
        }
    }

what I would like to do is to filter in the table "train trips" for the column full_departure_date with a range of dates but I can't get the function to execute in any way. Unfortunately, the Scope is not for me as I need to be able to run the filter all the time and not just in the presence of other.

Tucker-Eric commented 1 year ago

Shouldn't the model's function be prefixed with scope to be able to use the model's local scope. So renaming to scopeFrameDepartureDate would allow you to do the following in your filter:

    // assuming the $startDate and $endDate are found in the input as `start_date` and `end_date`
    public function frameDepartureDate($dateType)
    {
        switch ($dateType) {
            case 1: //departure date
                $formattedStartDate = Carbon::createFromFormat('d/m/Y', $this->input('start_date'));
                $formattedEndDate = Carbon::createFromFormat('d/m/Y', $this->input('end_date'));
                return $this->frameDepartureDate($formattedStartDate, $formattedEndDate);
        }
    }