[Laravel8.x] usersテーブルの値がNULLかのMiddlewareを作る

ここではemailが登録されているかの判定をし、登録されていなければ登録画面へ飛ばす
is_nullで判定する。

$ php artisan make:middleware RegisteredEmail
app/Http/Kernel.php

    protected $routeMiddleware = [
        // 省略
        'RegisteredEmail'=>\App\Http\Middleware\RegisteredEmail::class,
    ];

app/Http/Middleware/RegisteredEmail.php

use Illuminate\Support\Facades\Auth;
    public function handle(Request $request, Closure $next)
    {
       $user = Auth::user();
        if(is_null($user->email)){
            return redirect()->intended('/auth');
        }
        return $next($request);
    }

route

Route::group(['middleware' => ['auth','RegisteredEmail']], function(){
	Route::get('/email_test', [AdminController::class, 'emailTest']);
});

なるほど、登録されてなければ登録して、って処理は多いと思う

[MySQL8.0.22] Oracleのデータ型(NUMBERとDATE)を挿入する

OracleのNUMBER(16,4)とDATEをMySQLに挿入したい。

取り敢えずOracle側のテストデータとして以下を用意する。
2021/01/07 10:00:00
1500.0000

mysqlのCreate table

create table oracle_test(
	id int unsigned auto_increment primary key,
	price4 decimal(10,4),
	price2 decimal(10,2),
	datetime_at datetime,
	timestamp_at timestamp
);

mysql> describe oracle_test;
+————–+—————+——+—–+———+—————-+
| Field | Type | Null | Key | Default | Extra |
+————–+—————+——+—–+———+—————-+
| id | int unsigned | NO | PRI | NULL | auto_increment |
| price4 | decimal(10,4) | YES | | NULL | |
| price2 | decimal(10,2) | YES | | NULL | |
| datetime_at | datetime | YES | | NULL | |
| timestamp_at | timestamp | YES | | NULL | |
+————–+—————+——+—–+———+—————-+
5 rows in set (0.00 sec)

insert into oracle_test(price4) value("1500.0000");
insert into oracle_test(price2) value("1500.0000");
insert into oracle_test(datetime_at) value("2021/01/07 10:00:00");
insert into oracle_test(timestamp_at) value("2021/01/07 10:00:00");

mysql> select * from oracle_test;
+—-+———–+———+———————+———————+
| id | price4 | price2 | datetime_at | timestamp_at |
+—-+———–+———+———————+———————+
| 1 | 1500.0000 | NULL | NULL | NULL |
| 2 | NULL | 1500.00 | NULL | NULL |
| 3 | NULL | NULL | 2021-01-07 10:00:00 | NULL |
| 4 | NULL | NULL | NULL | 2021-01-07 10:00:00 |
+—-+———–+———+———————+———————+
4 rows in set (0.00 sec)

insert into oracle_test(price2) value(“1500.0050”);
| 5 | NULL | 1500.01 | NULL | NULL |

なるほど、mysql側で勝手に変換してくれんのか。
凄いけど、型づけ言語の考え方からいくと、型が完全に一致してないのに入るのは気持ち悪いな。
まあ、取り敢えず良しとしよう。

[Oracle] NUMBER型、DATE型をmysqlに挿入する

### NUMBER型(oracle)とDecimal型(mysql)
NUMBER型
L NUMBER(精度,位取り)単位で、精度:38桁、位取り:-84~127桁のデータを格納
Decimal型
L DECIMAL(精度,位取り)単位で、精度:65桁、位取り:0~30桁

-> 位取りが「負」の場合、あるいは「31以上」が指定されていた場合に桁あふれが発生する可能性あり

### OracleのDATE型とMySQLのtimestamp型、datetime型
DATE型
 L 年月日・時分秒単位で、西暦前4712年1月1日0時0分0秒~西暦9999年12月31日23時59分59秒の期間のデータを格納
date型
 L 年月日・時分秒・マイクロ秒単位で、西暦前1000年1月1日0時0分0.000001秒~西暦9999年12月31日23時59分59.999999秒の期間のデータを格納
-> 西暦前1000年1月1日0時0分0秒より古いデータの有無、及びナノ秒単位のデータの有無に注意する必要あり
datetime型
 L ‘1000-01-01 00:00:00’ ~ ‘9999-12-31 23:59:59’
timestamp型
L ‘1970-01-01 00:00:01’ UTC ~ ‘2038-01-19 03:14:07’ UTC

なんやと、データ連携って、データベースがOracleとMySQLだと全然単純な話じゃないんだな。
参ったぜ。

[PHP7.4.16] CSVからKeyとValueの連想配列を作る

まず、CSVにデータがある

このデータを元に連想配列を作る

$data = [];
$fp = fopen("Book.csv", "r");
while(! feof($fp)){
	$csv = fgets($fp);
	$csv = trim($csv,'"');
	$csv = mb_convert_encoding($csv, "UTF-8", "utf-8");
	$csv = str_replace('"','',$csv);
	$array = explode(",",$csv);
	$data[$array[0]] = $array[1];
}

echo "<pre>";
var_dump($data);
echo "</pre>";

まあOKっぽい。。

[Oracle] VARCHARとVARCHAR2の違い

– オラクルの型に、VARCHARとVARCHAR2があるが、VARCHARは古い文字列型で、VARCHAR2はそれを拡張して作られた新しい文字列型
– VARCHARデータ型は、VARCHAR2データ型と同義

なるほど、違いはないのね。。

[Laravel8.x] maatwebsite/excelのExcel出力時にスタイリング

maatwebsite/excelを使ってExcelを出力する際に、stylingをしたい。

export.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <style>
  .hoge {
    color: green;
  }
</style>
</head>
<body>
  <table>
  <thead>
  <tr>
    <th class="hoge">id</th>
    <th>name</th>
    <th>email</th>
  </tr>
  </thead>
  <tbody>
    @foreach ($users as $user)
    <tr>
      <td class="hoge">{{$user->id}}</td>
      <td style="color:red;">{{$user->name}}</td>
      <td>{{$user->email}}</td>
    </tr>
    @endforeach
  </tbody>
</table>
</body>
</html>


これだと、classで定義したcolorがexcel上に反映されない。
致し方がない、inlineで書くか。

### inline

<th style="background-color:#FF0000;color:#fff">id</th>

なるほど。

[PHP7.4.11] 配列の先頭から複数の値を取り出す

$animals = ["cat", "dog", "tiger","rabbit"];
$animals = array_slice($animals, 1, 3);

var_dump($animals);

array(3) { [0]=> string(3) “dog” [1]=> string(5) “tiger” [2]=> string(6) “rabbit” }

例えば、値が2つしかなくて、3つ取り出そうとしたら、

$animals = ["cat", "dog"];
$animals = array_slice($animals, 0, 3);

var_dump($animals);

array(2) { [0]=> string(3) “cat” [1]=> string(3) “dog” }

値がないときはnullとなる。
OK!

[Laravel8.x] csvではなくExcel(xlsx)を出力する

### ライブラリインストール
$ composer require maatwebsite/excel

app/config.php

'providers' => [
    Maatwebsite\Excel\ExcelServiceProvider::class,
],
'aliases' => [
    'Excel' => Maatwebsite\Excel\Facades\Excel::class,
],

$ php artisan vendor:publish –provider=”Maatwebsite\Excel\ExcelServiceProvider”

$ php artisan make:export Export
app/Exports/Export.php

namespace App\Exports;

// use Maatwebsite\Excel\Concerns\FromCollection;
use Illuminate\Contracts\View\View;
use Maatwebsite\Excel\Concerns\FromView;

class Export implements FromView
{
    /**
    * @return \Illuminate\Support\Collection
    */
    // public function collection()
    // {
    //     //
    // }
    private $view;

    public function __contruct(View $view){
    	$this->view = $view;
    }

    public function view(): View {
    	return $this->view;
    }
}

routing

Route::get('/export', [App\Http\Controllers\AdminController::class, 'export']);

controller

use App\Http\Requests\UserFormRequest;
use App\Exports\Export;

    public function export(){
        $users = User::get();
        $view = view('admin.export', compact('users'));
        return \Excel::download(new Export($view), 'users.xlsx');
    }

export.blade.php

<table>
  <thead>
  <tr>
    <th>id</th>
    <th>name</th>
    <th>email</th>
  </tr>
  </thead>
  <tbody>
    @foreach ($users as $user)
    <tr>
      <td>{{$user->id}}</td>
      <td>{{$user->name}}</td>
      <td>{{$user->email}}</td>
    </tr>
    @endforeach
  </tbody>
</table>

ほうほう、中々デキる、こやつ