Skip to content

Commit fe1f927

Browse files
committed
Laravel excel import
1 parent 5f04340 commit fe1f927

File tree

6 files changed

+224
-73
lines changed

6 files changed

+224
-73
lines changed

README.md

+12-72
Original file line numberDiff line numberDiff line change
@@ -1,79 +1,19 @@
1-
<p align="center"><img src="https://res.cloudinary.com/dtfbvvkyp/image/upload/v1566331377/laravel-logolockup-cmyk-red.svg" width="400"></p>
1+
# Laravel Excel Export & Import example
22

3-
<p align="center">
4-
<a href="https://travis-ci.org/laravel/framework"><img src="https://travis-ci.org/laravel/framework.svg" alt="Build Status"></a>
5-
<a href="https://packagist.org/packages/laravel/framework"><img src="https://poser.pugx.org/laravel/framework/d/total.svg" alt="Total Downloads"></a>
6-
<a href="https://packagist.org/packages/laravel/framework"><img src="https://poser.pugx.org/laravel/framework/v/stable.svg" alt="Latest Stable Version"></a>
7-
<a href="https://packagist.org/packages/laravel/framework"><img src="https://poser.pugx.org/laravel/framework/license.svg" alt="License"></a>
8-
</p>
3+
It's pretty easy to export to Excel and import from Excel, with great Laravel Excel package. This package supercharge your Laravel collections and export them directly to an Excel or CSV document.
94

10-
## About Laravel
5+
In the tutorial videos, you will learn:
116

12-
Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experience to be truly fulfilling. Laravel takes the pain out of development by easing common tasks used in many web projects, such as:
7+
- How to format exported columns
8+
- How to add header or additional columns
9+
- How to handle date formats, formulas etc.
10+
- How to process large files
11+
- How to catch exceptions and validate import data
1312

14-
- [Simple, fast routing engine](https://laravel.com/docs/routing).
15-
- [Powerful dependency injection container](https://laravel.com/docs/container).
16-
- Multiple back-ends for [session](https://laravel.com/docs/session) and [cache](https://laravel.com/docs/cache) storage.
17-
- Expressive, intuitive [database ORM](https://laravel.com/docs/eloquent).
18-
- Database agnostic [schema migrations](https://laravel.com/docs/migrations).
19-
- [Robust background job processing](https://laravel.com/docs/queues).
20-
- [Real-time event broadcasting](https://laravel.com/docs/broadcasting).
13+
## 1. Laravel Excel Export Tutorial
2114

22-
Laravel is accessible, powerful, and provides tools required for large, robust applications.
15+
[![Laravel Excel Export data in Excel](http://i3.ytimg.com/vi/VUet2wq22-o/hqdefault.jpg "Laravel Excel Export data in Excel")](https://www.youtube.com/watch?v=VUet2wq22-o "Laravel Excel Export data in Excel, CSV & multiple sheet export")
2316

24-
## Learning Laravel
17+
## 2. Laravel Excel Import Tutorial
2518

26-
Laravel has the most extensive and thorough [documentation](https://laravel.com/docs) and video tutorial library of all modern web application frameworks, making it a breeze to get started with the framework.
27-
28-
If you don't feel like reading, [Laracasts](https://laracasts.com) can help. Laracasts contains over 1500 video tutorials on a range of topics including Laravel, modern PHP, unit testing, and JavaScript. Boost your skills by digging into our comprehensive video library.
29-
30-
## Laravel Sponsors
31-
32-
We would like to extend our thanks to the following sponsors for funding Laravel development. If you are interested in becoming a sponsor, please visit the Laravel [Patreon page](https://patreon.com/taylorotwell).
33-
34-
- **[Vehikl](https://vehikl.com/)**
35-
- **[Tighten Co.](https://tighten.co)**
36-
- **[Kirschbaum Development Group](https://kirschbaumdevelopment.com)**
37-
- **[64 Robots](https://64robots.com)**
38-
- **[Cubet Techno Labs](https://cubettech.com)**
39-
- **[Cyber-Duck](https://cyber-duck.co.uk)**
40-
- **[Many](https://www.many.co.uk)**
41-
- **[Webdock, Fast VPS Hosting](https://www.webdock.io/en)**
42-
- **[DevSquad](https://devsquad.com)**
43-
- [UserInsights](https://userinsights.com)
44-
- [Fragrantica](https://www.fragrantica.com)
45-
- [SOFTonSOFA](https://softonsofa.com/)
46-
- [User10](https://user10.com)
47-
- [Soumettre.fr](https://soumettre.fr/)
48-
- [CodeBrisk](https://codebrisk.com)
49-
- [1Forge](https://1forge.com)
50-
- [TECPRESSO](https://tecpresso.co.jp/)
51-
- [Runtime Converter](http://runtimeconverter.com/)
52-
- [WebL'Agence](https://weblagence.com/)
53-
- [Invoice Ninja](https://www.invoiceninja.com)
54-
- [iMi digital](https://www.imi-digital.de/)
55-
- [Earthlink](https://www.earthlink.ro/)
56-
- [Steadfast Collective](https://steadfastcollective.com/)
57-
- [We Are The Robots Inc.](https://watr.mx/)
58-
- [Understand.io](https://www.understand.io/)
59-
- [Abdel Elrafa](https://abdelelrafa.com)
60-
- [Hyper Host](https://hyper.host)
61-
- [Appoly](https://www.appoly.co.uk)
62-
- [OP.GG](https://op.gg)
63-
- [云软科技](http://www.yunruan.ltd/)
64-
65-
## Contributing
66-
67-
Thank you for considering contributing to the Laravel framework! The contribution guide can be found in the [Laravel documentation](https://laravel.com/docs/contributions).
68-
69-
## Code of Conduct
70-
71-
In order to ensure that the Laravel community is welcoming to all, please review and abide by the [Code of Conduct](https://laravel.com/docs/contributions#code-of-conduct).
72-
73-
## Security Vulnerabilities
74-
75-
If you discover a security vulnerability within Laravel, please send an e-mail to Taylor Otwell via [[email protected]](mailto:[email protected]). All security vulnerabilities will be promptly addressed.
76-
77-
## License
78-
79-
The Laravel framework is open-sourced software licensed under the [MIT license](https://opensource.org/licenses/MIT).
19+
[![Laravel Excel Import to Database](http://i3.ytimg.com/vi/Q2AUH9w9XaA/hqdefault.jpg "Laravel Excel Import to Database")](https://www.youtube.com/watch?v=Q2AUH9w9XaA "Laravel Excel Import to Database with Errors and Validation Handling")
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
<?php
2+
3+
namespace App\Http\Controllers;
4+
5+
use App\Imports\UsersImport;
6+
use Illuminate\Http\Request;
7+
8+
class UsersImportController extends Controller
9+
{
10+
public function show()
11+
{
12+
return view('users.import');
13+
}
14+
15+
public function store(Request $request)
16+
{
17+
$file = $request->file('file')->store('import');
18+
19+
$import = new UsersImport;
20+
$import->import($file);
21+
22+
if ($import->failures()->isNotEmpty()) {
23+
return back()->withFailures($import->failures());
24+
}
25+
26+
27+
return back()->withStatus('Import in queue, we will send notification after import finished.');
28+
}
29+
}

app/Imports/UsersImport.php

+74
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
<?php
2+
3+
namespace App\Imports;
4+
5+
use App\User;
6+
use Illuminate\Contracts\Queue\ShouldQueue;
7+
use Illuminate\Support\Collection;
8+
use Illuminate\Support\Facades\Hash;
9+
use Maatwebsite\Excel\Concerns\Importable;
10+
use Maatwebsite\Excel\Concerns\RegistersEventListeners;
11+
use Maatwebsite\Excel\Concerns\SkipsErrors;
12+
use Maatwebsite\Excel\Concerns\SkipsFailures;
13+
use Maatwebsite\Excel\Concerns\SkipsOnError;
14+
use Maatwebsite\Excel\Concerns\SkipsOnFailure;
15+
use Maatwebsite\Excel\Concerns\ToCollection;
16+
use Maatwebsite\Excel\Concerns\ToModel;
17+
use Maatwebsite\Excel\Concerns\WithBatchInserts;
18+
use Maatwebsite\Excel\Concerns\WithChunkReading;
19+
use Maatwebsite\Excel\Concerns\WithEvents;
20+
use Maatwebsite\Excel\Concerns\WithHeadingRow;
21+
use Maatwebsite\Excel\Concerns\WithValidation;
22+
use Maatwebsite\Excel\Events\AfterImport;
23+
use Maatwebsite\Excel\Validators\Failure;
24+
use Throwable;
25+
26+
class UsersImport implements
27+
ToCollection,
28+
WithHeadingRow,
29+
SkipsOnError,
30+
WithValidation,
31+
SkipsOnFailure,
32+
WithChunkReading,
33+
ShouldQueue,
34+
WithEvents
35+
{
36+
use Importable, SkipsErrors, SkipsFailures, RegistersEventListeners;
37+
38+
39+
public function collection(Collection $rows)
40+
{
41+
foreach ($rows as $row) {
42+
$user = User::create([
43+
'name' => $row['name'],
44+
'email' => $row['email'],
45+
'password' => Hash::make('password')
46+
]);
47+
48+
$user->address()->create([
49+
'country' => $row['country']
50+
]);
51+
}
52+
}
53+
54+
public function rules(): array
55+
{
56+
return [
57+
'*.email' => ['email', 'unique:users,email']
58+
];
59+
}
60+
61+
62+
public function chunkSize(): int
63+
{
64+
return 1000;
65+
}
66+
67+
public static function afterImport(AfterImport $event)
68+
{
69+
}
70+
71+
public function onFailure(Failure ...$failure)
72+
{
73+
}
74+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
<?php
2+
3+
use Illuminate\Database\Migrations\Migration;
4+
use Illuminate\Database\Schema\Blueprint;
5+
use Illuminate\Support\Facades\Schema;
6+
7+
class CreateJobsTable extends Migration
8+
{
9+
/**
10+
* Run the migrations.
11+
*
12+
* @return void
13+
*/
14+
public function up()
15+
{
16+
Schema::create('jobs', function (Blueprint $table) {
17+
$table->bigIncrements('id');
18+
$table->string('queue')->index();
19+
$table->longText('payload');
20+
$table->unsignedTinyInteger('attempts');
21+
$table->unsignedInteger('reserved_at')->nullable();
22+
$table->unsignedInteger('available_at');
23+
$table->unsignedInteger('created_at');
24+
});
25+
}
26+
27+
/**
28+
* Reverse the migrations.
29+
*
30+
* @return void
31+
*/
32+
public function down()
33+
{
34+
Schema::dropIfExists('jobs');
35+
}
36+
}
+69
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
@extends('layouts.app')
2+
3+
@section('content')
4+
<div class="container">
5+
<div class="row justify-content-center">
6+
<div class="col-md-8">
7+
<div class="card">
8+
<div class="card-header">Import Excel</div>
9+
10+
<div class="card-body">
11+
@if (session('status'))
12+
<div class="alert alert-success" role="alert">
13+
{{ session('status') }}
14+
</div>
15+
@endif
16+
17+
@if (isset($errors) && $errors->any())
18+
<div class="alert alert-danger">
19+
@foreach ($errors->all() as $error)
20+
{{ $error }}
21+
@endforeach
22+
</div>
23+
@endif
24+
25+
@if (session()->has('failures'))
26+
27+
<table class="table table-danger">
28+
<tr>
29+
<th>Row</th>
30+
<th>Attribute</th>
31+
<th>Errors</th>
32+
<th>Value</th>
33+
</tr>
34+
35+
@foreach (session()->get('failures') as $validation)
36+
<tr>
37+
<td>{{ $validation->row() }}</td>
38+
<td>{{ $validation->attribute() }}</td>
39+
<td>
40+
<ul>
41+
@foreach ($validation->errors() as $e)
42+
<li>{{ $e }}</li>
43+
@endforeach
44+
</ul>
45+
</td>
46+
<td>
47+
{{ $validation->values()[$validation->attribute()] }}
48+
</td>
49+
</tr>
50+
@endforeach
51+
</table>
52+
53+
@endif
54+
55+
<form action="/users/import" method="post" enctype="multipart/form-data">
56+
@csrf
57+
58+
<div class="form-group">
59+
<input type="file" name="file" />
60+
61+
<button type="submit" class="btn btn-primary">Import</button>
62+
</div>
63+
</form>
64+
</button>
65+
</div>
66+
</div>
67+
</div>
68+
</div>
69+
@endsection

routes/web.php

+4-1
Original file line numberDiff line numberDiff line change
@@ -21,4 +21,7 @@
2121
Auth::routes();
2222

2323
Route::get('/home', 'HomeController@index')->name('home');
24-
Route::get('/users/export', 'UsersExportController@export');
24+
Route::get('/users/export', 'UsersExportController@export');
25+
26+
Route::get('/users/import', 'UsersImportController@show');
27+
Route::post('/users/import', 'UsersImportController@store');

0 commit comments

Comments
 (0)