export csv in laravel


how to export csv in laravel

 

step 1: make a view file and paste the button on-click event code and javascript code..

<body>

    <a href="{{url('/')}}/csvexport">

        <button type="button" onclick="exportTasks(event.target);">csv</button>

    </a>

</body>

 

<script>

   function exportTasks(_this) {

      let _url = $(_this).data('href');

      window.location.href = _url;

   }

</script>

 

step 2:  make a route in web.php file

Route::get('/csvexport',[csvController::class,'export']);

 

step 3: make a controller named as csvControlller, note: make a model named as ‘Allmails’ and import inside your csnController file

class csvController extends Controller

{

   function export(Request $request){

    $fileName = 'tasks.csv';

    $mails = Allemails::all();

 

         $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"

         );

 

         $columns = array('name', 'date');

 

         $callback = function() use($mails, $columns) {

             $file = fopen('php://output', 'w');

             fputcsv($file, $columns);

 

             foreach ($mails as $mail) {

                 $row['name']  = $mail->name;

                 $row['date']  = $mail->date;

 

                 fputcsv($file,array($row['name'],$row['date']));

             }

 

             fclose($file);

         };

 

         return response()->stream($callback, 200, $headers);

   }

}

 

 

Note: alwayes mentioned which type of data are you want to export !!

Popular posts from this blog

MCSL 216 MCA NEW Practical ~ common questions suggestions

dev chaeatsheet

STRAPI