2

I want to filter data between two dates in laravel. I have table with column date where date is stored in Y-m-d format.

$total = App\Models\Data::where('age_id',$age->id)
            ->where('nationality',$nationality)
            ->when(isset($to), function($q){
                $q->whereBetween('dateTime',[$from,$to]);
            })->when(!isset($to), function($q){
                $q->where('dateTime',$from);
            })
            ->sum('count');

My condition is that $to sometimes can be null. But whereBetween requires both $from and $to for it to work. And whereIn fetch data of $from and $to but not between $from and $to. If only $from is filled I want to filter data on that requested date. And if $from and $to is filled I want to filter data between $from and $to and perform count on those data. How can I achieve that?

3 Answers 3

3

Try this :

$data = App\Models\Data::where('age_id',$age->id)
            ->where('nationality', $nationality)
            ->when(isset($to), function($q) use($from, $to){
                $q->whereBetween('date', [$from, $to]);
            })
           ->when(!isset($to), function($q) use($from){
                $q->whereDate('date', $from);
            })
          ->get();
Sign up to request clarification or add additional context in comments.

1 Comment

instead of get can I use sum because i am summing here
1

For this you can assign a value for $to when is null, for example:

if (!$to) {
    $to = now();
}

$data = Data::whereBetween('date',[$from, $to])->get();

Comments

1

Eloquent comes with a when() function that can choose when parts of the query need to be executed.

$data = Data::when(isset($to), function($q){
            $q->whereBetween('date', [$from, $to]);
        })->when(!isset($to), function($q){
            $q->whereDate('date', $from);
        })->get();

4 Comments

I am getting undefined variable $from now
I have edited my function, can you please see that
use this if($request->from){ $dates=$this->dateFilter($request->from,$request->to); $from=$dates[0]; $to=$dates[1]; }
where should I use that

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.