Hi Guys,
In this tutorial will learn How to Import and Export an Excel File in Laravel 10. I will tell you the best way to Import and Export an Excel File in Laravel 10. If you want to see an example of import and export Excel file in Laravel 10 then you are in the right place at the right time.
For importing and exporting Excel files, we will use maatwebsite/excel composer package. in this tutorial, We will create a simple form for input where we can upload a CSV file and create multiple users. Then we will create an export route so we can download all users from the database in an Excel (.csv, .xls, and .xlsx) files.
so, let's follow the below steps to create the import and export function in Laravel 10 application. you can export files with .csv, .xls, and .xlsx files.
We will complete this tutorial in the below steps:
Step 1: Install Laravel 10
composer create-project laravel/laravel example-app
Step 2: Install maatwebsite/excel Package
In this step, we will install maatwebsite/excel package via the Composer package manager.
composer require maatwebsite/excel
php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider"
Step 3: Create Dummy Records
In this step, we will create some dummy data records for the user's table, so we can export them with those users. so let's run below tinker command:
php artisan tinker
User::factory()->count(10)->create();
Step 4: Create Import Class
In this step, we will create an import class. So you have to run the following command and change the following code on that file:
php artisan make:import UsersImport --model=User
<?php
namespace App\Imports;
use App\Models\User;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Hash;
class UsersImport implements ToModel, WithHeadingRow
{
/**
* @param array $row
*
* @return \Illuminate\Database\Eloquent\Model|null
*/
public function model(array $row)
{
return new User([
'name' => $row['name'],
'email' => $row['email'],
'password' => Hash::make($row['password']),
]);
}
}
Step 5: Create Export Class
In this step, we will create an export class. So you have to run the following command and change the following code on that file:
php artisan make:export UsersExport --model=User
<?php
namespace App\Exports;
use App\Models\User;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
class UsersExport implements FromCollection, WithHeadings
{
/**
* @return \Illuminate\Support\Collection
*/
public function collection()
{
return User::select("id", "name", "email")->get();
}
/**
* Write code on Method
*
* @return response()
*/
public function headings(): array
{
return ["ID", "Name", "Email"];
}
}
Step 6: Create Controller
In this step, we will create a UserController with index(), export(), and import() methods. so first let's create a controller by following the command and updating the code on it.
php artisan make:controller UserController
Now, update the code on the UserController file.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Exports\UsersExport;
use App\Imports\UsersImport;
use Maatwebsite\Excel\Facades\Excel;
use App\Models\User;
class UserController extends Controller
{
/**
* @return \Illuminate\Support\Collection
*/
public function index()
{
$users = User::get();
return view('users', compact('users'));
}
/**
* @return \Illuminate\Support\Collection
*/
public function export()
{
return Excel::download(new UsersExport, 'users.xlsx');
}
/**
* @return \Illuminate\Support\Collection
*/
public function import()
{
Excel::import(new UsersImport,request()->file('file'));
return back();
}
}
Step 7: Create Routes
In this step, we will create routes for a list of users, import users, and export users.
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::controller(UserController::class)->group(function(){
Route::get('users', 'index');
Route::get('users-export', 'export')->name('users.export');
Route::post('users-import', 'import')->name('users.import');
});
Step 8: Create Blade File
In the Last step, let's create users.blade.php(resources/views/users.blade.php) for layout and we will write design code here and put the following code:
<!DOCTYPE html>
<html>
<head>
<title>How to Import Excel File in Laravel - Om Coding Tutorial</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="card bg-light mt-3">
<div class="card-header">
How to Import Excel File in Laravel - Om Coding Tutorial
</div>
<div class="card-body">
<form action="{{ route('users.import') }}" method="POST" enctype="multipart/form-data">
@csrf
<input type="file" name="file" class="form-control">
<br>
<button class="btn btn-success">Import User Data</button>
</form>
<table class="table table-bordered mt-3">
<tr>
<th colspan="3">
List Of Users
<a class="btn btn-warning float-end" href="{{ route('users.export') }}">Export User Data</a>
</th>
</tr>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
</tr>
@foreach($users as $user)
<tr>
<td>{{ $user->id }}</td>
<td>{{ $user->name }}</td>
<td>{{ $user->email }}</td>
</tr>
@endforeach
</table>
</div>
</div>
</div>
</body>
</html>
Now we have done all the steps, you have to type the given below command and hit enter to run the Laravel app:
php artisan serve
Now, Go to your web browser, type the given URL, and view the app output
http://localhost:8000/users
I hope it can help you guys...
0 Comments
Leave a Comment