12
10

More than 5 years have passed since last update.

Laravel 5.4 に Google Analytics APIを実装

Last updated at Posted at 2017-05-06

前提

  1. Laravelの動作を一通り理解している事
  2. Google Analytics APIの基礎を理解している事
  3. Laravelのページ用のGoogle Analyticsの設定が済んでいる事

参考ページ

spatie/laravel-analyticsのインストール

$ composer require spatie/laravel-analytics
config/app.php
前略
'providers' => [
    ...
    Spatie\Analytics\AnalyticsServiceProvider::class,
    ...
];
中略
'aliases' => [
    ...
    'Analytics' => Spatie\Analytics\AnalyticsFacade::class,
    ...
];
後略
$ php artisan vendor:publish --provider="Spatie\Analytics\AnalyticsServiceProvider"

実行すると以下のファイルが作成される。

config/analytics.php
return [

    /*
     * The view id of which you want to display data.
     */
    'view_id' => env('ANALYTICS_VIEW_ID'),

    /*
     * Path to the client secret json file. Take a look at the README of this package
     * to learn how to get this file.
     */
    'service_account_credentials_json' => storage_path('app/analytics/service-account-credentials.json'),

    /*
     * The amount of minutes the Google API responses will be cached.
     * If you set this to zero, the responses won't be cached at all.
     */
    'cache_lifetime_in_minutes' => 60 * 24,

    /*
     * Here you may configure the "store" that the underlying Google_Client will
     * use to store it's data.  You may also add extra parameters that will
     * be passed on setCacheConfig (see docs for google-api-php-client).
     * 
     * Optional parameters: "lifetime", "prefix"
     */
    'cache' => [
        'store' => 'file',
    ],
];

spatie/laravel-analyticsの設定

Google Analytics APIの画面からcredentialsファイルを取得する

credentialsファイル(JSON形式)をダウンロードしたら、storage/app/analytics/service-account-credentials.jsonとして保存。このファイルはgitの管理下ではないのでデプロイの際に注意。

Google Analyticsの画面からcredentialsファイルで設定されているメールアドレスに権限を付与する

credentialsファイルを開き、client_emailをコピーし、Google Analyticsの管理画面でそのメールアドレスに「表示と分析」の権限を付与する。

ビューIDを確認する

Google Analyticsの管理画面でLaravelの画面用のビューIDを確認する。この値を.envに記載する。(ここでは例としてビューIDが123456789の場合を示します)

.env
ANALYTICS_VIEW_ID=123456789

Laravelでの利用方法(基礎)

ここでは管理画面のトップページにGoogle Analyticsの内容を表示するコントローラを考えてみます。

app/Http/Controllers/Admin/HomeController.php
<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Spatie\Analytics\AnalyticsClientFactory;
use Spatie\Analytics\Analytics;
use Spatie\Analytics\Period;

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $client = AnalyticsClientFactory::createForConfig(config('analytics'));
        $ga     = new Analytics($client, config('analytics.view_id'));

        // 期間中のユニークユーザー数とPV
        $gaData = $ga->fetchTotalVisitorsAndPageViews(Period::days(7));

        return view('admin.home')->with('ga', $gaData);
    }
}

あとはViewでよしなに。

12
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
10