SlideShare a Scribd company logo
Laravel 8
Export
Data as
Excel File
with
Example
www.bacancytechnology.com
Introduction
We have seen a few Laravel tutorials for
beginners and through one of our blog
posts, we received a query- Laravel 8 export
data excel file with example. So here we are
with another Laravel tutorial!


In this step-by-step guideline of Laravel 8
export data as excel file, we will build a
demo application in which we will use the
maatwebsite/excel package for exporting
data. You might be familiar with the
package; it provides the best way for
exporting the data as a CSV file or Excel file.


We will build a demo application where we
will see how to implement Excel export
functionality in Laravel using the
maatwebsite/excel package.
Tutorial Goal:
Laravel 8
Export Data
as Excel File
with Example
Before starting the development part, let’s
see the below video so that you can have an
idea of what are we going to build in this
blog.
Create a
Model with
Migration
// Student.php
< ? php
namespace AppModels;
use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;
class Student extends Model
{
use HasFactory;
public $fillable = [
'id',
'name',
'email',
'city'
];
}
Run this command to create a modal


php artisan make:model Student -m
Here we have to store the student data to
create a table and define the table’s fields.
Create a Data
Table
Go to the database/migration folder, then open
the migration file and write the following code.


//2021_07_16_041455_create_students_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 will create a table using the above fields.


Now run this command. This command is
useful for creating actual tables in the GUI
and migrating tables in the database.
php artisan migrate
Install
maatwebsite/
excel package
To install maatwebsite/excel, run the
below-mentioned command


composer require maatwebsite/excel.
With the help of this package, we can export
data into an excel file.


Now open config/app.php and add service
provider and alias.


'providers' => [
....
MaatwebsiteExcelExcelServiceProvider::c
lass,
],
'aliases' => [
....
'Excel' =>
MaatwebsiteExcelFacadesExcel::class,
],
Define the
routes
Routes are required for navigating the web
pages for defining routes in our demo app,
open routes/web.php, and use the following
code.


// web.php
Route::resource('student',StudentController
::class);
Route::get('student_export'[StudentControl
ler::class, 'get_student_data'])-
>name('student.export');
Create an
Export Class
In this section, we will create an export
class and define the model to which it is
connected. The maatwebsite package offers
a way for building an export class so that we
can further use it in the controller.


Run the below command for the same.


php artisan make:export StudentExport --
model=Student
Here StudentExport class will define the
data that we want to export in our excel file.
Go to app/Exports/ StudentExport.php and
make the following changes in your code
// StudentExport.php
<?php
namespace AppExports;
use AppModelsStudent;
use
MaatwebsiteExcelConcernsWithHeading
s;
use
MaatwebsiteExcelConcernsFromCollecti
on;
class StudentExport implements
FromCollection,WithHeadings
{
/**
* @return IlluminateSupportCollection
*/
public function headings():array{
return[
'Id',
'Name',
'Email',
'City',
'Created_at',
'Updated_at'
];
}
public function collection()
{
return Student::all();
}
}
The heading() function will define the
heading, which would be displayed in an excel
file.


The collection() method will return the data
which we have to export. Here in our demo
app, we will export all student data using the
Student Model.
Create
Controller
Before creating the controller we have to
make a request.


The command for creating a request.


php artisan make::request
StoreStudentRequest
Here are the validation rules applied for
entering student data.


public function rules()
{
return [
'name' =>
'bail|required|string|max:255',
'email' =>
'bail|required|string|email|max:255',
'city' => 'bail|required|string|max:255'
];
}
}
Run this command to create a resource
controller for writing the logic.
php artisan make:controller
StudentController –resource
Go to
app/Http/Controllers/StudentController.p
hp and write a code.


// StudentController.php
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 IlluminateHttpResponse
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified
resource.
*
* @param int $id
* @return IlluminateHttpResponse
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in
storage.
*
* @param IlluminateHttpRequest
$request
* @param int $id
* @return IlluminateHttpResponse
*/
public function update(Request $request,
$id)
{
//
}
/**
* Remove the specified resource from
storage.
*
* @param int $id
* @return IlluminateHttpResponse
*/
public function destroy($id)
{
//
}
public function get_student_data()
{
return Excel::download(new
StudentExport, 'students.xlsx');
}
}
Now we will use the download method of
the Laravel excel package within the
get_student_data() function. It will accept
two parameters: export class and name of
the file (you can name it anything you want)


The second parameter is the name of the file
in which we want to export the data.
The create() function is used to create
the form.
The store() method is used to store the
data in the database
The index() method is used to display
the data.
Create a View
to Add
Records and
Display
Details
Go to the resources/views folder. Create a
new folder layout with a file named a
main.blade.php


// main.blade.php
<!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/bootstra
p@5.0.2/dist/css/bootstrap.min.css"
rel="stylesheet" integrity="sha384-
EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1
ztcQTwFspd3yD65VohhpuuCOmLASjC"
crossorigin="anonymous">href="https://c
dn.jsdelivr.net/npm/bootstrap@5.0.2/dist/
css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-
EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Y
z1ztcQTwFspd3yD65VohhpuuCOmLASjC"
crossorigin="anonymous">
<title>@yield('title')</title>
</head>
<body>
@yield('content')
<script
src="https://cdn.jsdelivr.net/npm/bootstr
ap@5.0.2/dist/js/bootstrap.bundle.min.js"
integrity="sha384-
MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1
UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
crossorigin="anonymous"
/>
</body>
</html>
Now create another folder within the views
folder named student. We have to add the
records of the student, and for that, we will
need forms. Forms are defined in the view
file.


Here main.blade.php is the parent layout file
containing all the common header and
footer.


In the Student folder, create two files,
namely: create.blade.php and
index.blade.php.


The create.blade.php file is required to create
the form so that students can enter the data.
Open create.blade.php and write the
following code.


//create.blade.php
@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
In the index.blade.php file, we have
displayed the Student data in the table
format, and we can easily download the
data and export it as an excel file by
clicking the Export button.


// index.blade.php
@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
Run the Demo
Application
The last section of the tutorial- laravel 8
export data as excel file is to run the app.
Now it’s time to run our demo. Run the
below command.


php artisan serve
After running the server successfully you
can see the app working on


http://localhost:8000/student/create
GitHub
Repository
The entire source code is available here:
laravel-excel-export-example. Feel free to
clone the repo and play around with the
code.
Conclusion
So, I hope the tutorial of laravel 8 export
data as excel file was helpful to you. Are you
a laravel enthusiast and find it difficult for
basic tutorials? If yes, then the Laravel
tutorials page is for you! Feel free to visit
and explore more such laravel tutorials.


Bacancy has dedicated, skilled, and
experienced laravel developers with
problem-solving skills. If you are looking for
laravel developers who can help you with
your requirements and project then
without wasting your time contact Bacancy
and hire laravel developer.
Thank You
www.bacancytechnology.com

More Related Content

What's hot

Laravel overview
Laravel overviewLaravel overview
Laravel overview
Obinna Akunne
 
Começando com Vue.js
Começando com Vue.jsComeçando com Vue.js
Começando com Vue.js
marcusbalbi
 
Html 5 tags
Html  5 tagsHtml  5 tags
Html 5 tags
Eagle Eyes
 
Aula 7 expressão regular
Aula 7   expressão regularAula 7   expressão regular
Aula 7 expressão regular
wab030
 
Test Gap Analysis and regression minimization with Drill4j. Observability on ...
Test Gap Analysis and regression minimization with Drill4j. Observability on ...Test Gap Analysis and regression minimization with Drill4j. Observability on ...
Test Gap Analysis and regression minimization with Drill4j. Observability on ...
Dmitriy Gumeniuk
 
Estrutura de Dados - Listas Encadeadas
Estrutura de Dados - Listas EncadeadasEstrutura de Dados - Listas Encadeadas
Estrutura de Dados - Listas Encadeadas
Adriano Teixeira de Souza
 
#4 Primeiros comandos no MongoDB
#4   Primeiros comandos no MongoDB#4   Primeiros comandos no MongoDB
#4 Primeiros comandos no MongoDB
Gabriel Alves Scavassa
 
Exercícios - Herança - Java
Exercícios - Herança - JavaExercícios - Herança - Java
Exercícios - Herança - Java
Arthur Emanuel
 
Design Beautiful REST + JSON APIs
Design Beautiful REST + JSON APIsDesign Beautiful REST + JSON APIs
Design Beautiful REST + JSON APIs
Stormpath
 
Estruturas de dados com C++ e STL
Estruturas de dados com C++ e STLEstruturas de dados com C++ e STL
Estruturas de dados com C++ e STL
Marcos Castro
 
HTML5 Básico: Formulários (aula 2)
HTML5 Básico: Formulários (aula 2)HTML5 Básico: Formulários (aula 2)
HTML5 Básico: Formulários (aula 2)
Gustavo Zimmermann
 
Complexidade Ciclomática
Complexidade CiclomáticaComplexidade Ciclomática
Complexidade Ciclomática
Douglas Siviotti
 
Reactjs workshop (1)
Reactjs workshop (1)Reactjs workshop (1)
Reactjs workshop (1)
Ahmed rebai
 
Encapsulamento em Orientação a Objetos
Encapsulamento em Orientação a ObjetosEncapsulamento em Orientação a Objetos
Encapsulamento em Orientação a Objetos
Daniel Brandão
 
Angular - Chapter 9 - Authentication and Authorization
Angular - Chapter 9 - Authentication and AuthorizationAngular - Chapter 9 - Authentication and Authorization
Angular - Chapter 9 - Authentication and Authorization
WebStackAcademy
 
Coding standards for java
Coding standards for javaCoding standards for java
Coding standards for java
maheshm1206
 
FYBSC IT Web Programming Unit V Advanced PHP and MySQL
FYBSC IT Web Programming Unit V  Advanced PHP and MySQLFYBSC IT Web Programming Unit V  Advanced PHP and MySQL
FYBSC IT Web Programming Unit V Advanced PHP and MySQL
Arti Parab Academics
 
Curso de Desenvolvimento Web - Módulo 02 - CSS
Curso de Desenvolvimento Web - Módulo 02 - CSSCurso de Desenvolvimento Web - Módulo 02 - CSS
Curso de Desenvolvimento Web - Módulo 02 - CSS
Rodrigo Bueno Santa Maria, BS, MBA
 
JPA and Hibernate
JPA and HibernateJPA and Hibernate
JPA and Hibernate
elliando dias
 
Suppressing http headers from web sphere application server
Suppressing http headers from web sphere application serverSuppressing http headers from web sphere application server
Suppressing http headers from web sphere application server
Dave Hay
 

What's hot (20)

Laravel overview
Laravel overviewLaravel overview
Laravel overview
 
Começando com Vue.js
Começando com Vue.jsComeçando com Vue.js
Começando com Vue.js
 
Html 5 tags
Html  5 tagsHtml  5 tags
Html 5 tags
 
Aula 7 expressão regular
Aula 7   expressão regularAula 7   expressão regular
Aula 7 expressão regular
 
Test Gap Analysis and regression minimization with Drill4j. Observability on ...
Test Gap Analysis and regression minimization with Drill4j. Observability on ...Test Gap Analysis and regression minimization with Drill4j. Observability on ...
Test Gap Analysis and regression minimization with Drill4j. Observability on ...
 
Estrutura de Dados - Listas Encadeadas
Estrutura de Dados - Listas EncadeadasEstrutura de Dados - Listas Encadeadas
Estrutura de Dados - Listas Encadeadas
 
#4 Primeiros comandos no MongoDB
#4   Primeiros comandos no MongoDB#4   Primeiros comandos no MongoDB
#4 Primeiros comandos no MongoDB
 
Exercícios - Herança - Java
Exercícios - Herança - JavaExercícios - Herança - Java
Exercícios - Herança - Java
 
Design Beautiful REST + JSON APIs
Design Beautiful REST + JSON APIsDesign Beautiful REST + JSON APIs
Design Beautiful REST + JSON APIs
 
Estruturas de dados com C++ e STL
Estruturas de dados com C++ e STLEstruturas de dados com C++ e STL
Estruturas de dados com C++ e STL
 
HTML5 Básico: Formulários (aula 2)
HTML5 Básico: Formulários (aula 2)HTML5 Básico: Formulários (aula 2)
HTML5 Básico: Formulários (aula 2)
 
Complexidade Ciclomática
Complexidade CiclomáticaComplexidade Ciclomática
Complexidade Ciclomática
 
Reactjs workshop (1)
Reactjs workshop (1)Reactjs workshop (1)
Reactjs workshop (1)
 
Encapsulamento em Orientação a Objetos
Encapsulamento em Orientação a ObjetosEncapsulamento em Orientação a Objetos
Encapsulamento em Orientação a Objetos
 
Angular - Chapter 9 - Authentication and Authorization
Angular - Chapter 9 - Authentication and AuthorizationAngular - Chapter 9 - Authentication and Authorization
Angular - Chapter 9 - Authentication and Authorization
 
Coding standards for java
Coding standards for javaCoding standards for java
Coding standards for java
 
FYBSC IT Web Programming Unit V Advanced PHP and MySQL
FYBSC IT Web Programming Unit V  Advanced PHP and MySQLFYBSC IT Web Programming Unit V  Advanced PHP and MySQL
FYBSC IT Web Programming Unit V Advanced PHP and MySQL
 
Curso de Desenvolvimento Web - Módulo 02 - CSS
Curso de Desenvolvimento Web - Módulo 02 - CSSCurso de Desenvolvimento Web - Módulo 02 - CSS
Curso de Desenvolvimento Web - Módulo 02 - CSS
 
JPA and Hibernate
JPA and HibernateJPA and Hibernate
JPA and Hibernate
 
Suppressing http headers from web sphere application server
Suppressing http headers from web sphere application serverSuppressing http headers from web sphere application server
Suppressing http headers from web sphere application server
 

Similar to Laravel 8 export data as excel file with example

Exploring Symfony's Code
Exploring Symfony's CodeExploring Symfony's Code
Exploring Symfony's Code
Wildan Maulana
 
How to Create and Load Model in Laravel
How to Create and Load Model in LaravelHow to Create and Load Model in Laravel
How to Create and Load Model in Laravel
Yogesh singh
 
CodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkCodeIgniter PHP MVC Framework
CodeIgniter PHP MVC Framework
Bo-Yi Wu
 
Web technology Lab manual pdf.pdf
Web technology Lab manual pdf.pdfWeb technology Lab manual pdf.pdf
Web technology Lab manual pdf.pdf
preethihp4500
 
Task scheduling in laravel 8 tutorial
Task scheduling in laravel 8 tutorialTask scheduling in laravel 8 tutorial
Task scheduling in laravel 8 tutorial
Katy Slemon
 
Lecture 4_Laravel Controller and Data Pass-Route.pptx
Lecture 4_Laravel Controller and Data Pass-Route.pptxLecture 4_Laravel Controller and Data Pass-Route.pptx
Lecture 4_Laravel Controller and Data Pass-Route.pptx
SaziaRahman
 
Nodejs.meetup
Nodejs.meetupNodejs.meetup
Nodejs.meetup
Vivian S. Zhang
 
Java Airline Reservation System – Travel Smarter, Not Harder.pdf
Java Airline Reservation System – Travel Smarter, Not Harder.pdfJava Airline Reservation System – Travel Smarter, Not Harder.pdf
Java Airline Reservation System – Travel Smarter, Not Harder.pdf
SudhanshiBakre1
 
Php frameworks
Php frameworksPhp frameworks
Php frameworks
Anil Kumar Panigrahi
 
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016
Nicolás Bouhid
 
Flask – Python
Flask – PythonFlask – Python
Flask – Python
Max Claus Nunes
 
Yii Introduction
Yii IntroductionYii Introduction
Yii Introduction
Jason Ragsdale
 
18.register login
18.register login18.register login
18.register login
Razvan Raducanu, PhD
 
Web applications with Catalyst
Web applications with CatalystWeb applications with Catalyst
Web applications with Catalyst
svilen.ivanov
 
CICONF 2012 - Don't Make Me Read Your Mind
CICONF 2012 - Don't Make Me Read Your MindCICONF 2012 - Don't Make Me Read Your Mind
CICONF 2012 - Don't Make Me Read Your Mind
ciconf
 
Codeigniter : Two Step View - Concept Implementation
Codeigniter : Two Step View - Concept ImplementationCodeigniter : Two Step View - Concept Implementation
Codeigniter : Two Step View - Concept Implementation
Abdul Malik Ikhsan
 
blog_db_interface.phpphpinclude_once(blog_exceptions.
blog_db_interface.phpphpinclude_once(blog_exceptions.blog_db_interface.phpphpinclude_once(blog_exceptions.
blog_db_interface.phpphpinclude_once(blog_exceptions.
ChantellPantoja184
 
Rails 3 overview
Rails 3 overviewRails 3 overview
Rails 3 overview
Yehuda Katz
 
Rest hello world_tutorial
Rest hello world_tutorialRest hello world_tutorial
Rest hello world_tutorial
Aravindharamanan S
 
A multi submission importer for easyform
A multi submission importer for easyformA multi submission importer for easyform
A multi submission importer for easyform
Annette Lewis
 

Similar to Laravel 8 export data as excel file with example (20)

Exploring Symfony's Code
Exploring Symfony's CodeExploring Symfony's Code
Exploring Symfony's Code
 
How to Create and Load Model in Laravel
How to Create and Load Model in LaravelHow to Create and Load Model in Laravel
How to Create and Load Model in Laravel
 
CodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkCodeIgniter PHP MVC Framework
CodeIgniter PHP MVC Framework
 
Web technology Lab manual pdf.pdf
Web technology Lab manual pdf.pdfWeb technology Lab manual pdf.pdf
Web technology Lab manual pdf.pdf
 
Task scheduling in laravel 8 tutorial
Task scheduling in laravel 8 tutorialTask scheduling in laravel 8 tutorial
Task scheduling in laravel 8 tutorial
 
Lecture 4_Laravel Controller and Data Pass-Route.pptx
Lecture 4_Laravel Controller and Data Pass-Route.pptxLecture 4_Laravel Controller and Data Pass-Route.pptx
Lecture 4_Laravel Controller and Data Pass-Route.pptx
 
Nodejs.meetup
Nodejs.meetupNodejs.meetup
Nodejs.meetup
 
Java Airline Reservation System – Travel Smarter, Not Harder.pdf
Java Airline Reservation System – Travel Smarter, Not Harder.pdfJava Airline Reservation System – Travel Smarter, Not Harder.pdf
Java Airline Reservation System – Travel Smarter, Not Harder.pdf
 
Php frameworks
Php frameworksPhp frameworks
Php frameworks
 
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016
 
Flask – Python
Flask – PythonFlask – Python
Flask – Python
 
Yii Introduction
Yii IntroductionYii Introduction
Yii Introduction
 
18.register login
18.register login18.register login
18.register login
 
Web applications with Catalyst
Web applications with CatalystWeb applications with Catalyst
Web applications with Catalyst
 
CICONF 2012 - Don't Make Me Read Your Mind
CICONF 2012 - Don't Make Me Read Your MindCICONF 2012 - Don't Make Me Read Your Mind
CICONF 2012 - Don't Make Me Read Your Mind
 
Codeigniter : Two Step View - Concept Implementation
Codeigniter : Two Step View - Concept ImplementationCodeigniter : Two Step View - Concept Implementation
Codeigniter : Two Step View - Concept Implementation
 
blog_db_interface.phpphpinclude_once(blog_exceptions.
blog_db_interface.phpphpinclude_once(blog_exceptions.blog_db_interface.phpphpinclude_once(blog_exceptions.
blog_db_interface.phpphpinclude_once(blog_exceptions.
 
Rails 3 overview
Rails 3 overviewRails 3 overview
Rails 3 overview
 
Rest hello world_tutorial
Rest hello world_tutorialRest hello world_tutorial
Rest hello world_tutorial
 
A multi submission importer for easyform
A multi submission importer for easyformA multi submission importer for easyform
A multi submission importer for easyform
 

More from Katy Slemon

React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdfReact Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
Katy Slemon
 
Data Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdfData Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdf
Katy Slemon
 
How Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdfHow Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdf
Katy Slemon
 
What’s New in Flutter 3.pdf
What’s New in Flutter 3.pdfWhat’s New in Flutter 3.pdf
What’s New in Flutter 3.pdf
Katy Slemon
 
Why Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdfWhy Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdf
Katy Slemon
 
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdfHow Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
Katy Slemon
 
How to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdfHow to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdf
Katy Slemon
 
How to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdfHow to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdf
Katy Slemon
 
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdfSure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
Katy Slemon
 
How to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdfHow to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdf
Katy Slemon
 
IoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdfIoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdf
Katy Slemon
 
Understanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdfUnderstanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdf
Katy Slemon
 
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdfThe Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
Katy Slemon
 
New Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdfNew Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdf
Katy Slemon
 
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdfHow to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
Katy Slemon
 
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdfChoose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
Katy Slemon
 
Flutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdfFlutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdf
Katy Slemon
 
Angular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdfAngular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdf
Katy Slemon
 
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdfHow to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
Katy Slemon
 
Ruby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdfRuby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdf
Katy Slemon
 

More from Katy Slemon (20)

React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdfReact Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
 
Data Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdfData Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdf
 
How Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdfHow Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdf
 
What’s New in Flutter 3.pdf
What’s New in Flutter 3.pdfWhat’s New in Flutter 3.pdf
What’s New in Flutter 3.pdf
 
Why Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdfWhy Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdf
 
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdfHow Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
 
How to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdfHow to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdf
 
How to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdfHow to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdf
 
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdfSure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
 
How to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdfHow to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdf
 
IoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdfIoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdf
 
Understanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdfUnderstanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdf
 
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdfThe Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
 
New Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdfNew Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdf
 
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdfHow to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
 
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdfChoose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
 
Flutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdfFlutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdf
 
Angular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdfAngular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdf
 
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdfHow to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
 
Ruby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdfRuby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdf
 

Recently uploaded

Data structures and Algorithms in Python.pdf
Data structures and Algorithms in Python.pdfData structures and Algorithms in Python.pdf
Data structures and Algorithms in Python.pdf
TIPNGVN2
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
Adtran
 
Introducing Milvus Lite: Easy-to-Install, Easy-to-Use vector database for you...
Introducing Milvus Lite: Easy-to-Install, Easy-to-Use vector database for you...Introducing Milvus Lite: Easy-to-Install, Easy-to-Use vector database for you...
Introducing Milvus Lite: Easy-to-Install, Easy-to-Use vector database for you...
Zilliz
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
DianaGray10
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
shyamraj55
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
KAMESHS29
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
sonjaschweigert1
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
Matthew Sinclair
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems S.M.S.A.
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
Matthew Sinclair
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
Neo4j
 
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
Edge AI and Vision Alliance
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
James Anderson
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
SOFTTECHHUB
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
名前 です男
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
Uni Systems S.M.S.A.
 

Recently uploaded (20)

Data structures and Algorithms in Python.pdf
Data structures and Algorithms in Python.pdfData structures and Algorithms in Python.pdf
Data structures and Algorithms in Python.pdf
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
 
Introducing Milvus Lite: Easy-to-Install, Easy-to-Use vector database for you...
Introducing Milvus Lite: Easy-to-Install, Easy-to-Use vector database for you...Introducing Milvus Lite: Easy-to-Install, Easy-to-Use vector database for you...
Introducing Milvus Lite: Easy-to-Install, Easy-to-Use vector database for you...
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
 
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
 

Laravel 8 export data as excel file with example

  • 1. Laravel 8 Export Data as Excel File with Example www.bacancytechnology.com
  • 3. We have seen a few Laravel tutorials for beginners and through one of our blog posts, we received a query- Laravel 8 export data excel file with example. So here we are with another Laravel tutorial! In this step-by-step guideline of Laravel 8 export data as excel file, we will build a demo application in which we will use the maatwebsite/excel package for exporting data. You might be familiar with the package; it provides the best way for exporting the data as a CSV file or Excel file. We will build a demo application where we will see how to implement Excel export functionality in Laravel using the maatwebsite/excel package.
  • 4. Tutorial Goal: Laravel 8 Export Data as Excel File with Example
  • 5. Before starting the development part, let’s see the below video so that you can have an idea of what are we going to build in this blog.
  • 7. // Student.php < ? php namespace AppModels; use IlluminateDatabaseEloquentFactoriesHasFactory; use IlluminateDatabaseEloquentModel; class Student extends Model { use HasFactory; public $fillable = [ 'id', 'name', 'email', 'city' ]; } Run this command to create a modal php artisan make:model Student -m
  • 8. Here we have to store the student data to create a table and define the table’s fields.
  • 10. Go to the database/migration folder, then open the migration file and write the following code. //2021_07_16_041455_create_students_table id(); $table->string('name'); $table->string('email'); $table->string('city'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('students'); } }
  • 11. We will create a table using the above fields. Now run this command. This command is useful for creating actual tables in the GUI and migrating tables in the database. php artisan migrate
  • 13. To install maatwebsite/excel, run the below-mentioned command composer require maatwebsite/excel. With the help of this package, we can export data into an excel file. Now open config/app.php and add service provider and alias. 'providers' => [ .... MaatwebsiteExcelExcelServiceProvider::c lass, ], 'aliases' => [ .... 'Excel' => MaatwebsiteExcelFacadesExcel::class, ],
  • 15. Routes are required for navigating the web pages for defining routes in our demo app, open routes/web.php, and use the following code. // web.php Route::resource('student',StudentController ::class); Route::get('student_export'[StudentControl ler::class, 'get_student_data'])- >name('student.export');
  • 17. In this section, we will create an export class and define the model to which it is connected. The maatwebsite package offers a way for building an export class so that we can further use it in the controller. Run the below command for the same. php artisan make:export StudentExport -- model=Student Here StudentExport class will define the data that we want to export in our excel file. Go to app/Exports/ StudentExport.php and make the following changes in your code // StudentExport.php
  • 18. <?php namespace AppExports; use AppModelsStudent; use MaatwebsiteExcelConcernsWithHeading s; use MaatwebsiteExcelConcernsFromCollecti on; class StudentExport implements FromCollection,WithHeadings { /** * @return IlluminateSupportCollection */ public function headings():array{ return[ 'Id', 'Name', 'Email',
  • 19. 'City', 'Created_at', 'Updated_at' ]; } public function collection() { return Student::all(); } } The heading() function will define the heading, which would be displayed in an excel file. The collection() method will return the data which we have to export. Here in our demo app, we will export all student data using the Student Model.
  • 21. Before creating the controller we have to make a request. The command for creating a request. php artisan make::request StoreStudentRequest Here are the validation rules applied for entering student data. public function rules() { return [ 'name' => 'bail|required|string|max:255', 'email' => 'bail|required|string|email|max:255', 'city' => 'bail|required|string|max:255' ]; } }
  • 22. Run this command to create a resource controller for writing the logic. php artisan make:controller StudentController –resource Go to app/Http/Controllers/StudentController.p hp and write a code. // StudentController.php name = $request->name; $student->email = $request->email; $student->city = $request->city; $student->save(); return redirect(route('student.index'))- >with('success','Data submited successfully!'); }
  • 23. /** * Display the specified resource. * * @param int $id * @return IlluminateHttpResponse */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return IlluminateHttpResponse */ public function edit($id) { // }
  • 24. /** * Update the specified resource in storage. * * @param IlluminateHttpRequest $request * @param int $id * @return IlluminateHttpResponse */ public function update(Request $request, $id) { // } /** * Remove the specified resource from storage. * * @param int $id * @return IlluminateHttpResponse */
  • 25. public function destroy($id) { // } public function get_student_data() { return Excel::download(new StudentExport, 'students.xlsx'); } } Now we will use the download method of the Laravel excel package within the get_student_data() function. It will accept two parameters: export class and name of the file (you can name it anything you want) The second parameter is the name of the file in which we want to export the data.
  • 26. The create() function is used to create the form. The store() method is used to store the data in the database The index() method is used to display the data.
  • 27. Create a View to Add Records and Display Details
  • 28. Go to the resources/views folder. Create a new folder layout with a file named a main.blade.php // main.blade.php <!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/bootstra p@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384- EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1 ztcQTwFspd3yD65VohhpuuCOmLASjC"
  • 30. Now create another folder within the views folder named student. We have to add the records of the student, and for that, we will need forms. Forms are defined in the view file. Here main.blade.php is the parent layout file containing all the common header and footer. In the Student folder, create two files, namely: create.blade.php and index.blade.php. The create.blade.php file is required to create the form so that students can enter the data. Open create.blade.php and write the following code. //create.blade.php
  • 31. @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>
  • 32. <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
  • 33. In the index.blade.php file, we have displayed the Student data in the table format, and we can easily download the data and export it as an excel file by clicking the Export button. // index.blade.php @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>
  • 34. @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)
  • 35. <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
  • 37. The last section of the tutorial- laravel 8 export data as excel file is to run the app. Now it’s time to run our demo. Run the below command. php artisan serve After running the server successfully you can see the app working on http://localhost:8000/student/create
  • 39. The entire source code is available here: laravel-excel-export-example. Feel free to clone the repo and play around with the code.
  • 41. So, I hope the tutorial of laravel 8 export data as excel file was helpful to you. Are you a laravel enthusiast and find it difficult for basic tutorials? If yes, then the Laravel tutorials page is for you! Feel free to visit and explore more such laravel tutorials. Bacancy has dedicated, skilled, and experienced laravel developers with problem-solving skills. If you are looking for laravel developers who can help you with your requirements and project then without wasting your time contact Bacancy and hire laravel developer.