管理画面をいくら使いやすくしようとしても非エンジニアは、スプレッドシートが大好き。
そこでlaravel-adminからサクッと分析用のデータをスプレッドシートと連携したのでメモ
composer.jsonに以下を追加し、composer updateする。
"require": {
"php": ">=7.0.0",
"google/apiclient": "^2.0", // 追加
"guzzlehttp/guzzle": "^6.3",
"laravel/framework": "5.5.*",
"laravel/tinker": "~1.0",
},
laravel-adminのroutingにURL追加
$router->resource('/updateSheet', UpdateSheetsController::class);
GoogleSheetAPIをlaravel-admin配下に設置
require_once __DIR__.'../../../../vendor/autoload.php';
use Dotenv\Dotenv;
date_default_timezone_set('Asia/Tokyo');
class GoogleSheetsAPI
{
protected $service;
protected $spreadsheetId;
public function __construct()
{
$dotenv = new Dotenv(__dir__);
$dotenv->load();
$credentialsPath = getenv('SERVICE_KEY_JSON');
putenv('GOOGLE_APPLICATION_CREDENTIALS=' . dirname(__FILE__) . '/' . $credentialsPath);
$this->spreadsheetId = getenv('SPREADSHEET_ID');
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->addScope(Google_Service_Sheets::SPREADSHEETS);
$client->setApplicationName('test');
$this->service = new Google_Service_Sheets($client);
}
public function update($values = array(), $updatedRange)
{
$data = array();
$data[] = new \Google_Service_Sheets_ValueRange(array(
'range' => $updatedRange,
'values' => $values
));
$body = new \Google_Service_Sheets_BatchUpdateValuesRequest(array(
'valueInputOption' => 'USER_ENTERED',
'data' => $data
));
$response = $this->service->spreadsheets_values->batchUpdate($this->spreadsheetId, $body);
}
}
# .envファイルにgoogleアカウントから取得したSERVICE_KEY_JSON、SPREADSHEET_IDを追加
SERVICE_KEY_JSON=○○○.json
SPREADSHEET_ID=○○○
# スプレッドシート用のAPIを呼び出し
use GoogleSheetsAPI;
class UpdateSheetsController extends Controller
{
public function index()
{
$users = user::all();
$config_status = config('status');
$count = $users->count();
$row = 2;
foreach ($users as $user) {
$userInfo[] = array(
$user->id,
$user->email,
$user->address,
$user->phone_number,
$user->competitions->first()->id,
$user->competitions->first()->title,
$config_status[$user->competitions->first()->status],
$user->created_at->format('Y-m-d H:i'),
$user->competitions->first()->updated_at->format('Y-m-d H:i')
);
++$row;
}
$updatedRange = 'sheet!A2:L' . $row; // 範囲指定することで一括でコピー可能
$api = new GoogleSheetsAPI;
$api->update($userInfo, $updatedRange);
return Admin::content(function (Content $content) {
$content->body('<span><a href="https://docs.google.com/spreadsheets/d/シート番号/edit#gid=1840359659" target = "_blank">スプレッドシートを確認</a>');
});
}
とりあえずこれで管理画面のメニューを押したら一括でコピーできるようになりました。
本当はstatusをmodelでgetAttribute〜で定義して取得したいのですが、
laravel-adminだと取得できない。。。
やり方知っている方はアドバイスください。