What is the process for exporting MYSQL data within a specific date range using Laravel?

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');

Answer №1

If you're looking to export data from a Datatable, you'll be pleased to know that it comes with built-in functionality for exporting to CSV, PDF, and more. All you need to do is:

$('#order_table').DataTable( {
    dom: 'Bfrtlp',
    buttons: ['csv','pdf', 'excel','print']
} );

For more information and examples, check out the documentation here:

Answer №2

If you want to achieve this task, Laravel Excel is the way to go. Make sure to refer to the official documentation for detailed instructions:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Testing Laravel: Generating a fresh user profile

Attempting to test my sign up form in Laravel, I've encountered an issue. Here's what I'm doing: $this->visit('/auth/signup/free') ->type('First Name', 'first_name') ->type('<a ...

Is it possible for me to use AJAX to load content from a string? I am attempting to postpone the activation of certain HTML

I need help optimizing my HTML page that includes certain sections with large Javascript files and images, which are initially hidden. Even when set to "display: none," the browser still loads all the content. One solution could be moving those sections in ...

When tab switching occurs, the alert box fails to be processed by the browser

When using the alert(message) function, it will display an alert box with a message and an OK button. It will also pause the execution of any code that follows until the OK button is clicked. However, I have noticed a peculiar situation where switching tab ...

Tips for adjusting the alignment of the Vuetify component "VDatePicker" based on the position of its parent component on the screen

Currently, I am utilizing the VMenu component from Vuetify which contains another Vuetify component called VDatePicker. The issue arises when clicking on a text field triggers the appearance of the calendar (VDatePicker). Normally, the VDatePicker componen ...

Restricting zooming to only occur within the img element in a UI

Is there a method to enable image zoom inside specific divs without affecting the overall page zoom? At the moment, I have: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale ...

Navigating PopUpWindows using SeleniumIn this guide, learn the best

I have attempted to manage a particular PopUp / new Window in Java using SeleniumServer, but unfortunately, it is not functioning as expected. Here is what I have tried: selenium.click("css=a[title=\"Some irrelevant title\"] > div.text"); Thr ...

Conditionally render a div in React with Next.js depending on the value of a prop

Struggling with an issue in my app and seeking some guidance. The problem arises when dealing with data from contentful that has been passed as props to a component. Specifically, I only want to render a particular piece of data if it actually contains a v ...

JavaScript code snippet for detecting key presses of 3 specific arrow keys on the document

For this specific action, I must press and hold the left arrow key first, followed by the right arrow key, and then the up arrow key. However, it seems that the up arrow key is not being triggered as expected. It appears that there may be some limitations ...

What is the issue with retrieving a subselect field from another subselect query?

These are the tables I am working with: tbl_activity(id, name) tbl_activity_package(id, activity_id, name) tbl_activity_package_address(id, activity_package_id, district) When a user provides a district, I need to return a list of activities that take p ...

Modify nested JSON in JavaScript, much like how Ruby translations can interpret them (from a list or text)

I have a specific goal in mind. My JSON data is multi-level, structured like this: var json = { 'first_level': { 'second_level': ['one', 'two'] }, 'another_first_level': true } and I want ...

What is the best way to store an image in a database using only the file name as a VARCHAR?

Is there a way to avoid storing photos in the database due to memory storage concerns? I'd like to just store the file name and use it to access the photo instead. How can this be achieved? The code I have so far is not working as expected. Currently, ...

Execute the subtraction of data from one MySQL table to another table

Currently, I have two tables... One is called Freezing with columns (id, et1, straw, eps) and the other is Inventory with columns (id, et1, owner, total) I want a function where when something is entered into the 'EPS' column in Freezing, it wi ...

generating a dynamic string array containing particular elements

Given a string "hello @steph the email you requested is [email protected] for user @test" The goal is to transform it into: ['hello ', <a href="">@steph</a>, 'the email you requested is <a href="/cdn-cgi/l/email-protect ...

Utilizing Html.BeginCollectionItem helper to pass a collection with only a glimpse of the whole picture

After seeking guidance from Stephen Muecke on a small project, I have encountered an issue. The javascript successfully adds new fields from the Partial View and connects them to the model through "temp" values set by the controller method for the partial ...

I'm trying to integrate a chatbot into my website using Node-RED. Can someone guide me on how to utilize the Bluemix Tone Analyzer to analyze the tone of the user

Creating a chat bot to ask psychological questions and analyze how a person is feeling has been my recent project. I managed to set up a chat bot in Bluemix, following a tutorial on integrating it into Node Red: https://github.com/watson-developer-cloud/no ...

Ways to extract variables from a component and utilize them in App.js

Despite my efforts to search online, I could not find the answer or understand what I needed to. My issue: I need the "inputVal" variable from the "InputField.js" component to be accessible in the "App.js" component (specifically in the fetch request where ...

Incorporate a background image property using Jquery

Can anyone help me with adding the css background-image:url("xxxxx") property to my code? jQuery('#'+$trackID+' .sc_thumb').attr('src',$thumb_url); jQuery('#'+$trackID+' .sc_container').css('display& ...

Guide to accessing a method from a separate file with the help of an event bus

I'm working on CreateEntryStepper.vue where I have a button that needs to call a function in CreateEntryStepperImageUpload.vue when pressed. I understand that event busses need to be used, but I am unsure about what exactly needs to be passed and how ...

"Learn how to use jQuery to retrieve a specific row from an HTML table based on equality with a certain

I have a dynamically generated table using PHP. The information in this table is related to different semesters (such as first, second, third, etc.). I want to display specific semester information when a user clicks a link from the same table without need ...

Is there a way to change the format of a date and time from YYYY-MM-DD hh mm ss to MonthName, date, year | Hour:Minutes (am/pm) using

How can I convert the date string (2013-03-10 19:43:55) into the format (Mar 10, 2013 | 7:43 pm) using JavaScript or jQuery? ...