How to retrieve data in a date range from mysql database in Laravel?

删除回忆录丶 提交于 2020-01-16 08:23:11

问题


In my application, if someone clicks the Filter button I want to display data in a table format from mysql database, but here I am not receiving any responses. Please someone help me out with this.

custom_script.js

fetch_data();
    function fetch_data(from_date = '', to_date = '') {
        if(from_date != '' && to_date != '') {
               console.log(from_date+' | '+to_date)
        }

    }

    $('#filter').click(function() {
        var from_date = $('#from_date').val();
        var to_date = $('#to_date').val();
        if(from_date != '' && to_date != '') {
            fetch_data(from_date, to_date);
        }
        else {
            alert('Both Date is required');
        }
    });

    $('#refresh').click(function() {
        $('#from_date').val('');
        $('#to_date').val('');
        fetch_data();
    });

HolidayController.php

public function fetch_data(Request $request)
    {

        if($request->from_date != '' && $request->to_date != '') {
            $data = DB::table('holidays')
                ->whereBetween('startdate', 
                array($request->from_date, $request->to_date))
                ->get();
        }
        else {
            $data = DB::table('holidays')->orderBy('startdate', 'desc')
            ->get();
        }
        return response($data);
    }

回答1:


You can use it like these

$holiday = Holiday::where('from_date', '>=', $date)->where('to_date', '<=', $date)->get();



回答2:


Your fetch_data method in custom_script.js should be something like that as your previous script

function fetch_data(from_date = '', to_date = '') {
        $.ajax({
            url:"{{ route('holiday.fetch_data')}}",
            method:"POST",
            data:{
                from_date:from_date, to_date:to_date, _token:_token
            },
            dataType:"json",
            success:function(data) {
                var output = '';
                $('#total_records').text(data.length);
                for(var count = 0; count < data.length; count++) {
                    output += '<tr>';
                    output += '<td>' + data[count].id + '</td>';
                    output += '<td>' + data[count].firstname + '</td>';
                    output += '<td>' + data[count].lastname + '</td>';
                    output += '<td>' + data[count].startdate + '</td>';
                    output += '<td>' + data[count].enddate + '</td></tr>';
                }
                $('tbody').html(output);
            }
        })
    }

you used my script here,which i used for demonstration purpose.This is not workable code.You must need to make ajax request to the server to get some data as a response.



来源:https://stackoverflow.com/questions/59700663/how-to-retrieve-data-in-a-date-range-from-mysql-database-in-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!