This technical blog post will explore how to export student data to a CSV file in a Laravel application without using any package. We will cover the entire process, from defining routes to implementing the export functionality in the controller and creating a corresponding button in the Blade view.

Getting Started:

Prerequisites:

Before using this feature, ensure that you have the following:

  • Your Application – Make sure your application is up and running.
  • Composer – Dependency manager for PHP.

Installation:

No additional installation steps are required for this feature. It is integrated into your existing Laravel application.

Usage:

Accessing the Student Export:

To access the Student Export feature, follow these steps:

  • Log in to your application.
  • Navigate to the page where the export button is located.

Exporting Student Data:

  • On the designated page, locate the “Student Export” button.
  • Click on the button to initiate the export process.
  • A CSV file named “student.csv” will be downloaded automatically.

Code Overview:

Route

The route responsible for handling the student export is defined in your `web.php` file. It maps the `studentExport` method from the `StudentController` to the URL `/student-export`.

Route::get('/student-export', [StudentController::class, 'studentExport'])->name('student.studentExport');

Blade

The Blade template includes a button that links to the student export route. This button is styled using Bootstrap classes.

<div class="col-md-4 mb-3">    <a class="btn btn-warning btn-block text-white" href="{{route('student.studentExport')}}">       Student Export  </a></div>

Controller

The `StudentController` contains the `studentExport` method responsible for generating and streaming the CSV file. It retrieves student data, prepares the CSV content, and sends it to the user for download.

public function studentExport(){    // ... (see next section for detailed explanation)}

The `studentExport` method in the `StudentController` is responsible for generating and streaming the CSV file containing student data.

Explanation of the Controller Method:

Now, let’s break down the `studentExport` method and understand each part of the code.

$fileName = "student.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");

These lines set up the necessary headers for the CSV file download. The filename is defined as “student.csv” and headers are specified to indicate that the response is of type CSV.

$columns = array('Zone', 'Institution', 'Name', 'Roll');

An array of column headers for the CSV file is defined.

$callback = function() use($columns) {
    // ... (see next section for detailed explanation)
};

A callback function is defined to handle the streaming of CSV data.

$file = fopen('php://output', 'w');
fputcsv($file, $columns);
// ... (see next section for detailed explanation)
fclose($file);

This section of the code sets up the file resource, writes the column headers to the CSV file, and prepares for writing student data.

StudentProgress::query()    ->leftJoin('students','students.id','=','student_progress.student_id')    ->leftJoin('institutions', 'institutions.id', '=', 'student_progress.institution_id')    ->leftJoin('zones', 'zones.id', '=', 'institutions.zone_id')    ->select(        'student_progress.*','students.name as student_name','institutions.ims_institute_name',        'zones.name as zone_name'    )    ->orderBy('student_progress.institution_id','asc')    ->orderBy('student_progress.roll','asc')    ->chunk(2000, function ($results) use ($file) {        // Process each chunk of results        foreach ($results as  $item) {            $row['Zone'] = $item->zone_name;            $row['Institution'] = $item->ims_institute_name;            $row['Name'] = $item->student_name;            $row['Roll'] = $item->roll;
            fputcsv($file, array(                $row['Zone'],                $row['Institution'],                $row['Name'],                $row['Roll'],            ));        };    });

This part of the code retrieves student data using Laravel Eloquent relationships, selects relevant fields, orders the results, and processes the data in chunks. The student data is then written to the CSV file row by row.

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

The response()->stream method is used to initiate the streaming of the CSV file with the specified callback function and headers.

Two Types of Methods are Given below – Use any one

Full Code Of `studentExport` Method – Type 0ne:

public function studentExport(){   set_time_limit(1800); //if need, you can set    $fileName = "student.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",       "Accept-Ranges" => "bytes", //this Accept-Ranges header help you for pause download   );   $columns = array('Zone','Institution','Name','Roll');
   $callback= function() use($columns) {       $file = fopen('php://output', 'w');       fputcsv($file, $columns);
       StudentProgress::query()           ->leftJoin('students','students.id','=','student_progress.student_id')           ->leftJoin('institutions', 'institutions.id', '=', 'student_progress.institution_id')           ->leftJoin('zones', 'zones.id', '=', 'institutions.zone_id')              ->select(               'student_progress.*','students.name as student_name','institutions.ims_institute_name',               'zones.name as zone_name'           )           ->orderBy('student_progress.institution_id','asc')           ->orderBy('student_progress.roll','asc')           ->chunk(1500, function ($results) use ($file) {               // Process each chunk of results               foreach ($results as  $item) {                   $rowData = [                       $item->zone_name,                       $item->ims_institute_name,                                             $item->student_name,                       $item->roll,                   ];                   fputcsv($file, $rowData);               };           });       fclose($file);   };   return response()->stream($callback, 200, $headers);}

Full Code Of `studentExport` Method – Type Two:

public function studentExport(){   $fileName = "student.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"   );
   $columns = array('Name','Gender'  'Roll');
   $callback = function() use($columns) {
       $file = fopen('php://output', 'w');
       fputcsv($file, $columns);
       Student::query()           ->orderBy('roll','asc')           ->chunk(2000, function ($results) use ($file) {               // Process each chunk of results               foreach ($results as  $item) {                   $row['Name'] = $item->name;                   $row['Gender'] = $item->gender;                   $row['Roll'] = $item->roll;
                   fputcsv($file, array(                       $row['Name'],                       $row['Name'],                       $row['Roll'],                   ));               };           });       fclose($file);   };
   return response()->stream($callback, 200, $headers);  }

Conclusion

In this blog post, we’ve walked through the process of exporting student data to a CSV file in a Laravel application without using any package. By understanding the code structure and the role of each component, you should now be equipped to implement similar functionality in your Laravel projects. Feel free to customize the code to suit your specific requirements and enhance the export feature further. Happy coding!

This page was last edited on 28 July 2024, at 5:53 pm