|
| 1 | +## Importing basics |
| 2 | + |
| 3 | +If you have followed the 5 Minute Quickstart, you'll already have a `UsersImport` class. |
| 4 | + |
| 5 | +```php |
| 6 | +<?php |
| 7 | + |
| 8 | +namespace App\Imports; |
| 9 | + |
| 10 | +use App\User; |
| 11 | +use Illuminate\Support\Facades\Hash; |
| 12 | +use Maatwebsite\Excel\Concerns\ToModel; |
| 13 | + |
| 14 | +class UsersImport implements ToModel |
| 15 | +{ |
| 16 | + /** |
| 17 | + * @param array $row |
| 18 | + * |
| 19 | + * @return User|null |
| 20 | + */ |
| 21 | + public function model(array $row) |
| 22 | + { |
| 23 | + return new User([ |
| 24 | + 'name' => $row[0], |
| 25 | + 'email' => $row[1], |
| 26 | + 'password' => Hash::make($row[2]), |
| 27 | + ]); |
| 28 | + } |
| 29 | +} |
| 30 | +``` |
| 31 | + |
| 32 | +### Importing from default disk |
| 33 | + |
| 34 | +Passing the UsersImport object to the Excel::import() method, will tell the package how to import the file that is passed as second parameter. |
| 35 | +The file is expected to be located in your default filesystem disk (see config/filesystems.php). |
| 36 | + |
| 37 | +```php |
| 38 | +Excel::import(new UsersImport, 'users.xlsx'); |
| 39 | +``` |
| 40 | + |
| 41 | +### Importing from anther disk |
| 42 | + |
| 43 | +You can specify another disk with the third parameter like your Amazon s3 disk. (see config/filesystems.php) |
| 44 | + |
| 45 | +```php |
| 46 | +Excel::import(new UsersImport, 'users.xlsx', 's3'); |
| 47 | +``` |
| 48 | + |
| 49 | +### Importing uploaded files |
| 50 | + |
| 51 | +If you let your user upload the document, you can also just pass the uploaded file directly. |
| 52 | + |
| 53 | +```php |
| 54 | +Excel::import(new UsersImport, request()->file('your_file')); |
| 55 | +``` |
| 56 | + |
| 57 | +### Importing to array or collection |
| 58 | + |
| 59 | +If you want to bypass the `ToArray` or `ToCollection` concerns and want to have an array of imported data in your controller (beware of performance!), you can use the `::toArray()` or `::toCollection()` method. |
| 60 | + |
| 61 | +```php |
| 62 | +$array = Excel::toArray(new UsersImport, 'users.xlsx'); |
| 63 | + |
| 64 | +$collection = Excel::toCollection(new UsersImport, 'users.xlsx'); |
| 65 | +``` |
| 66 | + |
| 67 | +### Specifying a reader type |
| 68 | + |
| 69 | +If the reader type is not detectable by the file extension, you can specify a reader type by passing it as fourth parameter. |
| 70 | + |
| 71 | +```php |
| 72 | +Excel::import(new UsersImport, 'users.xlsx', 's3', \Maatwebsite\Excel\Excel::XLSX); |
| 73 | +``` |
0 commit comments