How do I export data to excel in Laravel PHP
Published January 17, 2022In this post, we will look at how we can export data to excel in Laravel PHP. We will use the maatwebsite/excel package to export our data. This package provides the best way to export data as Excel Files or CSV Files.
Exporting data to Excel in Laravel PHP
Step 1: First of all, create a new Laravel project using the command below
composer create-project --prefer-dist laravel/laravel LaravelExcel |
![]() |
A new project is installed on your server
Step 2: Run the command below to create a model with Migration: php artisan make: model Student -m
Now, let's create a table and define the table fields by storing information about students. We can do this by opening Student.php and pasting the code below
<? php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Student extends Model {
'id', 'name', 'email', 'city' ]; } |
Student.php
Step 3: Let's create a data table. Open the database/migration, then open the migration file 2022_01_14_225625_create_students_table.php
Paste the code below
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateStudentsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('students', function (Blueprint $table) { $table->id(); $table->string('name'); $table->string('email'); $table->string('city'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('students'); } } |
We are going to create a table using the fields above. To do this, run the following command
php artisan migrate |
Step 4: · Next, let's install the maatwebsite/excel package using the command below
composer require maatwebsite/excel |
With this package, we can export data into an Excel file. Now, open config/app.php and add an alias and service provider
'providers' => [ .... Maatwebsite\Excel\ExcelServiceProvider::class, ], 'aliases' => [ .... 'Excel' => Maatwebsite\Excel\Facades\Excel::class, ], |
Step 5: To enable navigating in our web pages, we’ll need to define routes. To do this, open routes/web.php and paste the code below
Route::resource('student', StudentController::class); Route::get('student_export',[StudentController::class, 'get_student_data'])->name('student.export'); |
Step 6: Let's create an export class and define the connected model by running the command below
php artisan make: export StudentExport --model=Student |
To export data to our Excel file, we need to go to app/Exports/StudentExport.php and paste the following code:
<?php namespace App\Exports; use App\Models\Student; use Maatwebsite\Excel\Concerns\WithHeadings; use Maatwebsite\Excel\Concerns\FromCollection; class StudentExport implements FromCollection,WithHeadings { /** * @return \Illuminate\Support\Collection */ public function headings():array{ return[ 'Id', 'Name', 'Email', 'City', 'Created_at', 'Updated_at' ]; } public function collection() { return Student::all(); } } |
-
Step 7: Now, let’s create a controller. First, run the command below to make a request. php artisan make::request StoreStudentRequest. Then, run this command to create the resource controller for writing the logic: php artisan make: controller StudentController –resource
Finally, open app/Http/Controllers/StudentController.php and paste the code below
<?php namespace App\Http\Controllers; use App\Models\Student; use Illuminate\Http\Request; use App\Exports\StudentExport; use Maatwebsite\Excel\Facades\Excel; use App\Http\Requests\StoreStudentRequest; class StudentController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $students = Student::paginate(5); return view('student.index',compact('students')); }
/** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view('student.create'); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(StoreStudentRequest $request) { $student = new Student; $student->name = $request->name; $student->email = $request->email; $student->city = $request->city; $student->save(); return redirect(route('student.index'))->with('success','Data submited successfully!'); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response*/ public function edit($id) {// } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) {// } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } public function get_student_data() { return Excel::download(new StudentExport, 'students.xlsx'); } } |
Step 8: Now let’s display our details and add record. To do this, create a file, main.blade.php, and paste the code below
<!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <title>@yield('title')</title> </head> <body> @yield('content') <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous" /> </body> </html> |
Create create.blade.php and paste the code below:
@extends('layout.main') @section('title') Registration form @endsection @section('content') <div class="container"> <h2 class="text-center mt-3">Student Registration Form</h2> <form action="{{ route('student.store') }}" method="POST"> @csrf <div class="mb-3"> <label for="Name" class="form-label">Name</label> <input type="text" class="form-control @error('name') is-invalid @enderror" id="name" name="name" value="{{ old('name') }}"> @error('name') <div class="text-danger">{{ $message }}</div> @enderror </div> <div class="mb-3"> <label for="email" class="form-label">Email</label> <input type="text" class="form-control @error('email') is-invalid @enderror" id="email" name="email" value="{{ old('email') }}"> @error('email') <div class="text-danger">{{ $message }}</div> @enderror </div> <div class="mb-3"> <label for="city" class="form-label">City</label> <input type="text" class="form-control @error('city') is-invalid @enderror" id="city" name="city" value="{{ old('city') }}"> @error('city') <div class="text-danger">{{ $message }}</div> @enderror </div> <button type="submit" class="btn btn-primary">Submit</button> </form> </div> @endsection |
Create index.blade.php and paste the code below
@extends('layout.main') @section('title') Student Data @endsection @section('content') <div class="container mt-3"> @if ($message = session('success')) <div class="alert alert-success mx-1" role="alert">{{ $message }} </div> @endif <h2 class=" text-center">Student Data</h2> <div class="mt-5"> <a href="{{ route('student.export') }}" class="btn btn-primary"> Export Data </a> <a href="{{ route('student.create') }}" class="btn btn-primary"> Add Data </a> </div> <table class="table table-hover mt-5"> <thead> <tr> <th>ID</th> <th>Name</th> <th>Email</th> <th>City</th> </tr> </thead> <tbody> @foreach ($students as $student) <tr> <td>{{ $student->id }}</td> <td>{{ $student->name }}</td> <td>{{ $student->email }}</td> <td>{{ $student->city }}</td> </tr> @endforeach </tbody> </table> <div class="mt-5"> {{ $students->links() }} </div> </div> @endsection |
We are done, let's run our application. It works as expected
Article Contributed By :
|
|
|
|
1209 Views |