TABLE OF CONTENTS

Subscribe for
weekly updates

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

Run this command to create a modal

Copy Text
php artisan make:model Student -m

// Student.php

Copy Text
<? php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Student extends Model
{
    use HasFactory;

    public $fillable = [
        'id',
        'name',
        'email',
        'city'
    ];
}

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

Copy Text
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.

Copy Text
php artisan migrate

Install maatwebsite/excel package

To install maatwebsite/excel, run the below-mentioned command

Copy Text
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.

Copy Text
'providers' => [
      ....
     Maatwebsite\Excel\ExcelServiceProvider::class,
],
'aliases' => [
      ....
     'Excel' => Maatwebsite\Excel\Facades\Excel::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

Copy Text
Route::resource('student', StudentController::class);
Route::get('student_export',[StudentController::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.

Copy Text
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

Copy Text
<?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();
    }
}

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.

Copy Text
php artisan make::request StoreStudentRequest

Here are the validation rules applied for entering student data.

Copy Text
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.

Copy Text
php artisan make:controller StudentController –resource

Go to app/Http/Controllers/StudentController.php and write a code.

// StudentController.php

Copy Text
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');
    }
}

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

Copy Text
<!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>

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

Copy Text
@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

Copy Text
@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.

Copy Text
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.

Laravel Tutorials

Connect Now

Get In Touch

[email protected]

Your Success Is Guaranteed !

We accelerate the release of digital product and guaranteed their success

We Use Slack, Jira & GitHub for Accurate Deployment and Effective Communication.