文書の過去の版を表示しています。
CSVファイルアップロード時に、バリデーションチェックを行い、DBに登録する方法の一例。
コンフィグファイルに、csv の列に対応した DB カラム名の関連付けを定義する。
<?php
return [
'csv_columns' => [
0 => 'number',
1 => 'title',
2 => 'name',
3 => 'age',
4 => 'comment',
],
];
csv 周りの処理をクラスにまとめておく。
<?php
namespace App\Libs;
class SampleCsv
{
private $file;
private $data = [];
public function __construct($path)
{
$this->file = new \SplFileObject($path);
}
public function convertColumns()
{
$count = 0;
while (!$this->file->eof()) {
$line = $this->file->fgetcsv(',', '\'');
$count ++;
if (!$line || is_null($line[0])) {
continue;
}
mb_convert_variables('UTF-8', 'sjis-win', $line);
$tmp = [];
foreach ($line as $key => $val) {
$column_name = config('site.csv.csv_columns')[$key];
$tmp[$column_name] = $val;
}
$this->data[$count] = $this->revise($tmp);
}
return $this->data;
}
// 入力内容の補正
private function revise($inputs)
{
foreach ($inputs as $key => $input) {
switch ($key) {
case 'number':
case 'age':
// 全角英数を半角に
$input = mb_convert_kana($input, 'as');
break;
}
$inputs[$key] = $input;
}
return $inputs;
}
public function validationRules()
{
return [
'number' => 'bail|required|integer|between:0,999999999',
'title' => 'bail|required|max:100',
'name' => 'bail|required|max:50',
'age' => 'bail|required|integer|between:0,150',
'comment' => 'bail|max:1000',
];
}
public function validationMessages()
{
return [
];
}
public function validationAttributes()
{
return [
'number' => 'No',
'title' => 'タイトル',
'name' => '名前',
'age' => '年齢',
'comment' => 'コメント',
];
}
}
以下、記事まとめ途中
コメント