I have been struggling with a problem that might seem simple to some of you. I am able to filter out data based on a date range and display it in the view.
However, I now need to export these searched/filtered results in CSV/Excel format. It would be incredibly helpful if someone could help me solve this issue.
Thank you very much!
DateRangeController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
class DateRangeController extends Controller
{
function index(Request $request)
{
if(request()->ajax())
{
if(!empty($request->from_date))
{
$data = DB::table('users_info')
->whereBetween('ptdate', array($request->from_date, $request->to_date))->get();
}
else
{
$data = DB::table('users_info')->get();
}
return datatables()->of($data)->make(true);
}
return view('daterange');
}
}
?>
daterange.blade.php
<div class="row input-daterange">
<div class="col-md-2">
<input type="text" name="from_date" id="from_date" class="form-control" placeholder="From Date" readonly />
</div>
<div class="col-md-2">
<input type="text" name="to_date" id="to_date" class="form-control" placeholder="To Date" readonly />
</div>
<div class="col-md-4">
<button type="button" name="filter" id="filter" class="btn btn-primary">Filter</button>
<button type="button" name="refresh" id="refresh" class="btn btn-default">Refresh</button>
</div>
</div>
<script>
$(document).ready(function(){
$('.input-daterange').datepicker({
todayBtn:'linked',
format:'yyyy-mm-dd',
autoclose:true
});
load_data();
function load_data(from_date = '', to_date = '')
{
$('#order_table').DataTable({
processing: true,
serverSide: true,
ajax: {
url:'{{ route("daterange.index") }}',
data:{from_date:from_date, to_date:to_date}
},
});
}
$('#filter').click(function(){
var from_date = $('#from_date').val();
var to_date = $('#to_date').val();
if(from_date != '' && to_date != '')
{
$('#order_table').DataTable().destroy();
load_data(from_date, to_date);
}
else
{
alert('Both Date is required');
}
});
$('#refresh').click(function(){
$('#from_date').val('');
$('#to_date').val('');
$('#order_table').DataTable().destroy();
load_data();
});
});
</script>
Route.php
Route::get('/daterange', 'DateRangeController@index');
Route::post('/daterange', 'DateRangeController@export');
Route::resource('daterange', 'DateRangeController');