简体   繁体   中英

Laravel - get records between two dates with ajax

I use Laravel and I want to get records between two dates. In frontend I use daterangepicker and I write:

$('#reportrange').on('apply.daterangepicker', function(ev, picker) {
  var start = picker.startDate.format('YYYY-MM-DD');
  var end = picker.endDate.format('YYYY-MM-DD');

 $.ajaxSetup({
                headers: {
                    'X-XSRF-Token': $('meta[name="_token"]').attr('content')
                }
            });

            $.ajax({
        type: "POST",
                url   : '{{url()}}/getOrders',
data: {start: start, end: end},
                cache : false,

                beforeSend : function() {
                    console.log('krece');
                },

                success : function(data) {
                    console.log(data);

                },

                error : function() {

                }
            });


});

so I try to send start and end date and get dates between and in Laravel I have :

route:

Route::post('/getOrders', 'OrdersController@getOrders');

and in OrdersController:

    public function getOrders(Request $request) {
    $start = $request->start;
    $end = $request->end;

//ALSO NEED QUESRY WHICH WILL FETCH ROWS BETWEEN DATES
//$orders = Auth::user()->orders()->get(); ... ...

    return $orders;

    }

now when I choose some dates in daterangepicker I get:

 POST http://localhost:8888/getOrders 500 (Internal Server Error)

What is a problem?

Off cource in header I put:

  <meta name="csrf-token" content="{{ csrf_token() }}" />

How to get records between dates ith Laravel and jquery ajax?

You can take the use of whereBetween() to get results between dates:

$orders = Auth::user()
            ->orders()
            ->whereBetween('created_at', [$start_date, $end_date])
            ->get();

Hope this helps!

For the query you can do as:

$orders = Auth::user()->orders()
                      ->whereBetween('created_at', array($start, $end))
                      ->get();

And for the 500 (Internal Server Error) you can check your laravel.log file.

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