Search code examples
phpjqueryajaxlaravelexport-to-csv

Export only selected rows into csv in Laravel


I have to export only the selected rows using checkbox into csv here is my code. I am using ajax to pass multiple user id to the controller but I don't know how to export only passing user ids please help the problem is, it is just returning an empty excel file

enter image description here

Export Csv button

<a data-href="/admin/export/selected/data" class="btn btn-filter btn-secondary" id="export_records">Export
            Selected</a>

enter image description here

Ajax code for multiple select

    <script>
    $(document).on('click', '#selectAll', function() {

        $(".user_checkbox").prop("checked", this.checked);
        $("#select_count").html($("input.user_checkbox:checked").length + " Selected");
    });
    $(document).on('click', '.user_checkbox', function() {

        if ($('.user_checkbox:checked').length == $('.user_checkbox').length) {
            $('#selectAll').prop('checked', true);
        } else {
            $('#selectAll').prop('checked', false);
        }
        $("#select_count").html($("input.user_checkbox:checked").length + " Selected");
    });
    $(document).ready(function() {
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });

        $('#export_records').on('click', function(e) {
            var user = [];
            $(".user_checkbox:checked").each(function() {
                user.push($(this).data('user-id'));
            });
            if (user.length <= 0) {
                alert("Please select records.");
            } else {


                var selected_values = user;
                $.ajax({
                    type: "get",
                    url: "{{ route('export.csv') }}",
                    cache: false,
                    data: 'user_id=' + selected_values,
                    success: function(response) {

                        let _url = $("#export_records").data('href');
                        window.location.href = _url;
                    }
                });
            }

        });

    });

</script>

Controller to download csv

 public function exportCsv(Request $request)
{
    $users = User::whereIn('id', explode(",", $request->user_id))->get();
    $filename = "UsersData.csv";
    $headers = array(
        'Content-Type' => 'text/csv',
        "Content-Disposition" => "attachment; filename=$filename",
        "Pragma"              => "no-cache",
        "Cache-Control"       => "must-revalidate, post-check=0, pre-check=0",
        "Expires"             => "0"
    );
    $callback = function() use($filename, $users) {
    $handle = fopen('php://output', 'w');
    fputcsv($handle, array('name','email', 'company_name','role', 'created_at'));

    foreach ($users as $user) {
            $row['name']  = $user->name;
            $row['email']    = $user->email;
            $row['company_name']    = $user->company_name;
            $row['role']  = $user->roles->name;
            $row['created_at']  = $user->created_at;
        fputcsv($handle, array($row['name'], $row['email'], $row['company_name'], $row['role'], $row['created_at']->format('l jS \of F Y')));
    }

    fclose($handle);
};
    

    return Response::stream($callback, 200, $headers);
}

Note this code is working for all user data export in csv like $users = User::all() but not working with selected ones

ajax response

enter image description here


Solution

  • hopefully, I got the solution I was just missing the URL with window.location.href I also had to pass user_id with it. so here is the modified part,

    $.ajax({
          type: "GET",
           url: "{{ route('exportOption.Userscsv') }}",
           cache: false,
           data: 'user_id=' + selected_values,
           success: function(response) {
              let _url = $("#export_records").data('href');
              var selected_values = user;
              window.location.href = _url + '?user_id=' + selected_values;
    
                        }
               });
    

    Hope it will be helpful for you guys.