简体   繁体   中英

How to sort data between two dates using query() function in laravel

Here is my controller:

$my_query = Deathregister::query();
foreach ($request->query() as $key => $value) 
{
    $my_query->where($key, $value);
}
$my_query->get();

Now if i pass 'fromdate = 2020-10-30' and 'todate = 2021-11-07' i want all the data in bwtween these days. Is this possible?

You can use CarbonPeriod class of PHP. To use it in Laravel

import it first

use Carbon\CarbonPeriod;

Then in the controller function use

$period = CarbonPeriod::create($request->from_dt,'1 day', $request->to_dt);

foreach ($period as $value) {
   $reqDate =  $value->format('d-M-Y');
   //$reqDate will have the date you can change the format as per your requirement
}

You can use whereDate() method:

Deathregister::whereDate('date_field','>=', $request->input('fromdate'))
    ->whereDate('date_field','<=', $request->input('todate'))
    ->get();

The below code worked for me to sort date by given all the parameter with date.

$q = $request->query();
if ($q != NULL) {
    $fromdate = $request->fromdate;
    $todate = $request->todate;
    $my_query = Movementregister::query();
    if ($fromdate != NULL and $todate != NULL) {
        if (!empty($q['type'])) {
            $my_query->where('type', $q['type']);
        }
        if (!empty($q['issue'])) {
            $my_query->where('issue', $q['issue']);
        }
        $my_query->whereBetween('created_at', [$fromdate, $todate]);
     } else {
        foreach ($request->query() as $key => $value) {
            $my_query->where($key, $value);
        }
  }
  $data = $my_query->get();
  return response()->json(["message" => "Success", "data" => $data], 200);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM