LaravelでEXCELを読み込む方法について、下記のサイトを見ながら試したので、そのメモです。
バージョンはLaravel 8.10.0で、ConoHaのLaravelテンプレートでインストールしました。
リンク先には出力方法もかかれているので、usersテーブルについてはこの方法でうまくいきました。
Laravel 8 Import Export Excel and CSV File Tutorial – ItSolutionStuff.com
リンクサイトでは、最初からあるUserモデルでやっていますが、私はDeviceというモデルに、devicesテーブルをつくり、そのデータをEXCELで読み込むやり方を試しました。
maatwebsite/excel Packageをインストールする
ターミナルから、maatwebsite/excelをインストールします。
$ composer require maatwebsite/excel
config/app.phpにて、service providerとaliaseに下記のように追記します。
‘providers’ => [
Maatwebsite\Excel\ExcelServiceProvider::class,
],
‘aliases’ => [
‘Excel’ => Maatwebsite\Excel\Facades\Excel::class,
],
モデルを作成
Deviceのモデルを作成します。
php artisan make:model Device
EXCELのデータを読み込む際、fillableに記述しておく必要があるので、下記のように記載。
use HasFactoryの下
protected $fillable = [
'deviceName', 'email', 'lastCheckin',
];
データベース migrationファイルを作成
devicesテーブルのmigrationファイルを作成します。
php artisan make:migration create_devices_table
migrationファイルには、devices テーブルの構造を記載します。
public function up()
{
Schema::create('devices', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email');
$table->string('date');
$table->timestamps();
});
}
migrateして、devicesテーブルを作成します。
$ php artisan migrate
Import Classをつくる
EXCELの内容をインポートする為のImport Classを作ります。
php artisan make:import DevicesImport –model=Device
このコマンドによって
app/Importsフォルダに、DevicesImport.phpが作成されます。
下記のように修正
namespace App\Imports;
use App\Models\Device;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
class DevicesImport implements ToModel,WithHeadingRow
{
/**
* @param array $row
*
* @return \Illuminate\Database\Eloquent\Model|null
*/
public function model(array $row)
{
//dd($row);
return new Device([
'name' => $row['name'],
'email' => $row['email'],
'date' => $row['date'],
]);
}
}
当初、WithHeadingRowを書き忘れたところ、EXCELファイルの一行目をキーとして読み込んでくれずにはまりました。みなさんは、忘れないように。
Controllerの作成
リンク先にあるとおり、
app/Http/Controllers/MyController.php
をつくります。
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Imports\DevicesImport;
use Maatwebsite\Excel\Facades\Excel;
class MyController extends Controller
{
/**
* @return \Illuminate\Support\Collection
*/
public function importExportView()
{
return view('import');
}
/**
* @return \Illuminate\Support\Collection
*/
public function import()
{
Excel::import(new DevicesImport,request()->file('file'));
return back();
}
}
web.phpの作成
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\MyController;
/*
|--------------------------------------------------------------------------
| 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::get('importExportView', [MyController::class, 'importExportView']);
Route::post('import', [MyController::class, 'import'])->name('import');
viewファイルの作成
resources/views/import.blade.php
を作成します。
*リンク先のviewファイルを少しだけ修正
<!DOCTYPE html>
<html>
<head>
<title>Laravel 8 Import Export Excel to database Example - ItSolutionStuff.com</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />
</head>
<body>
<div class="container">
<div class="card bg-light mt-3">
<div class="card-header">
Laravel 8 Import Export Excel to database Example - ItSolutionStuff.com
</div>
<div class="card-body">
<form action="{{ route('import') }}" method="POST" enctype="multipart/form-data">
@csrf
<input type="file" name="file" class="form-control">
<br>
<button class="btn btn-success">Import Device Data</button>
</form>
</div>
</div>
</div>
</body>
</html>
以上です。
あとは、ブラウザで
サイトURL/importExportView
を開けば、EXCELデータをインポートできます。
私は、Macのoffice365のxlsxデータで成功しました。
まとめ
これ、すごく便利です!