Readouble

Laravel 5.8 HTTPセッション

イントロダクションIntroduction

HTTP駆動のアプリケーションはステートレスのため、リクエスト間に渡りユーザーに関する情報を保存するセッションが提供されています。Laravelは記述的で統一されたAPIを使える様々なバックエンドのセッションを用意しています。人気のあるMemcachedRedis、データベースも始めからサポートしています。Since HTTP driven applications are stateless, sessions provide a way to store information about the user across multiple requests. Laravel ships with a variety of session backends that are accessed through an expressive, unified API. Support for popular backends such as Memcached[https://memcached.org], Redis[https://redis.io], and databases is included out of the box.

設定Configuration

セッションの設定はconfig/session.phpにあります。このファイルのオプションには詳しくコメントがついていますので確認して下さい。ほとんどのアプリケーションでうまく動作できるように、Laravelはfileセッションドライバをデフォルトとして設定しています。実働環境のアプリケーションではセッションの動作をより早くするために、memcachedredisドライバの使用を考慮しましょう。The session configuration file is stored at config/session.php. Be sure to review the options available to you in this file. By default, Laravel is configured to use the file session driver, which will work well for many applications. In production applications, you may consider using the memcached or redis drivers for even faster session performance.

セッションドライバ(driver)はリクエスト毎のセッションデータをどこに保存するかを決めます。Laravelには最初から素晴らしいドライバが用意されています。The session driver configuration option defines where session data will be stored for each request. Laravel ships with several great drivers out of the box:

- `file` - セッションは`storage/framework/sessions`に保存されます。 - `cookie` - セッションは暗号化され安全なクッキーに保存されます。 - `database` - セッションはリレーショナルデータベースへ保存されます。 - `memcached`/`redis` - セッションはスピードの早いキャッシュベースの保存域に保存されます。 - `array` - セッションはPHPの配列として保存されるだけで、リクエスト間で継続しません。

lightbulb">Tip!! セッションデータを持続させないため、arrayドライバは通常テスト時に使用します。{tip} The array driver is used during testing[/docs/{{version}}/testing] and prevents the data stored in the session from being persisted.

ドライバの事前要件Driver Prerequisites

データベースDatabase

databaseセッションドライバを使う場合、セッションアイテムを含むテーブルを作成する必要があります。以下にこのテーブル宣言のサンプル「スキーマ」を示します。When using the database session driver, you will need to create a table to contain the session items. Below is an example Schema declaration for the table:

Schema::create('sessions', function ($table) {
    $table->string('id')->unique();
    $table->unsignedInteger('user_id')->nullable();
    $table->string('ip_address', 45)->nullable();
    $table->text('user_agent')->nullable();
    $table->text('payload');
    $table->integer('last_activity');
});

session:table Artisanコマンドを使えば、このマイグレーションが生成できます。You may use the session:table Artisan command to generate this migration:

php artisan session:table

php artisan migrate

RedisRedis

RedisセッションをLaravelで使用する前に、Composerでpredis/predisパッケージ(~1.0)をインストールする必要があります。Redis接続はdatabase設定ファイルで設定します。session設定ファイルでは、connectionオプションで、どのRedis接続をセッションで使用するか指定します。Before using Redis sessions with Laravel, you will need to install the predis/predis package (~1.0) via Composer. You may configure your Redis connections in the database configuration file. In the session configuration file, the connection option may be used to specify which Redis connection is used by the session.

セッションの使用Using The Session

データ取得Retrieving Data

Laravelでセッションを操作するには、主に2つの方法があります。グローバルなsessionヘルパを使用する方法と、コントローラメソッドにタイプヒントで指定できるRequestインスタンスを経由する方法です。最初はRequestインスタンスを経由する方法を見てみましょう。コントローラのメソッドに指定した依存インスタンスは、Laravelのサービスコンテナにより、自動的に注入されることを覚えておきましょう。There are two primary ways of working with session data in Laravel: the global session helper and via a Request instance. First, let's look at accessing the session via a Request instance, which can be type-hinted on a controller method. Remember, controller method dependencies are automatically injected via the Laravel service container[/docs/{{version}}/container]:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
    /**
     * 指定されたユーザーのプロフィールを表示
     *
     * @param  Request  $request
     * @param  int  $id
     * @return Response
     */
    public function show(Request $request, $id)
    {
        $value = $request->session()->get('key');

        //
    }
}

getメソッドでセッションから値を取り出すとき、第2引数にデフォルト値も指定できます。このデフォルト値は、セッションに指定したキーが存在していなかった場合に、返されます。getメソッドのデフォルト値に「クロージャ」を渡した場合に、要求したキーが存在しなければ、その「クロージャ」が実行され、結果が返されます。When you retrieve an item from the session, you may also pass a default value as the second argument to the get method. This default value will be returned if the specified key does not exist in the session. If you pass a Closure as the default value to the get method and the requested key does not exist, the Closure will be executed and its result returned:

$value = $request->session()->get('key', 'default');

$value = $request->session()->get('key', function () {
    return 'default';
});

sessionグローバルヘルパThe Global Session Helper

グローバルなsession PHP関数で、セッションからデータを出し入れすることもできます。sessionヘルパが文字列ひとつだけで呼び出されると、そのセッションキーに対する値を返します。ヘルパがキー/値ペアの配列で呼び出されると、それらの値はセッションへ保存されます。You may also use the global session PHP function to retrieve and store data in the session. When the session helper is called with a single, string argument, it will return the value of that session key. When the helper is called with an array of key / value pairs, those values will be stored in the session:

Route::get('home', function () {
    // セッションから一つのデータを取得する
    $value = session('key');

    // デフォルト値を指定する場合
    $value = session('key', 'default');

    // セッションへ一つのデータを保存する
    session(['key' => 'value']);
});

lightbulb">Tip!! セッションをHTTPリクエストインスタンスを経由する場合と、グローバルなsessionヘルパを使用する場合では、実践上の違いがあります。どんなテストケースであろうとも使用可能な、assertSessionHasメソッドを利用して、どちらの手法もテスト可能です。{tip} There is little practical difference between using the session via an HTTP request instance versus using the global session helper. Both methods are testable[/docs/{{version}}/testing] via the assertSessionHas method which is available in all of your test cases.

全セッションデータの取得Retrieving All Session Data

セッション中の全データを取得する場合は、allメソッドを使います。If you would like to retrieve all the data in the session, you may use the all method:

$data = $request->session()->all();

セッション中のアイテム存在を確認Determining If An Item Exists In The Session

セッションへ値が存在するか調べたい場合は、hasメソッドを使います。その値が存在し、nullでない場合はtrueが返ります。To determine if an item is present in the session, you may use the has method. The has method returns true if the item is present and is not null:

if ($request->session()->has('users')) {
    //
}

セッション中に、たとえ値がnullであろうとも存在していることを確認したい場合は、existsメソッドを使います。existsメソッドは、値が存在していればtrueを返します。To determine if an item is present in the session, even if its value is null, you may use the exists method. The exists method returns true if the item is present:

if ($request->session()->exists('users')) {
    //
}

データ保存Storing Data

セッションへデータを保存する場合、通常putメソッドか、sessionヘルパを使用します。To store data in the session, you will typically use the put method or the session helper:

// リクエストインスタンス経由
$request->session()->put('key', 'value');

// グローバルヘルパ使用
session(['key' => 'value']);

配列セッション値の追加Pushing To Array Session Values

pushメソッドは新しい値を配列のセッション値へ追加します。たとえばuser.teamsキーにチーム名の配列が含まれているなら、新しい値を次のように追加できます。The push method may be used to push a new value onto a session value that is an array. For example, if the user.teams key contains an array of team names, you may push a new value onto the array like so:

$request->session()->push('user.teams', 'developers');

取得後アイテムを削除Retrieving & Deleting An Item

pullメソッド一つで、セッションからアイテムを取得後、削除できます。The pull method will retrieve and delete an item from the session in a single statement:

$value = $request->session()->pull('key', 'default');

フラッシュデータFlash Data

次のリクエスト間だけセッションにアイテムを保存したいことは良くあります。flashメソッドを使ってください。flashメソッドは直後のHTTPリクエストの間だけセッションにデータを保存します。それ以降は削除されます。フラッシュデータは主にステータスメッセージなど継続しない情報に便利です。Sometimes you may wish to store items in the session only for the next request. You may do so using the flash method. Data stored in the session using this method will only be available during the subsequent HTTP request, and then will be deleted. Flash data is primarily useful for short-lived status messages:

$request->session()->flash('status', 'Task was successful!');

フラッシュデータをその先のリクエストまで持続させたい場合は、reflashメソッドを使い、全フラッシュデータを次のリクエストまで持続させられます。特定のフラッシュデータのみ持続させたい場合は、keepメソッドを使います。If you need to keep your flash data around for several requests, you may use the reflash method, which will keep all of the flash data for an additional request. If you only need to keep specific flash data, you may use the keep method:

$request->session()->reflash();

$request->session()->keep(['username', 'email']);

データ削除Deleting Data

forgetメソッドでセッションからデータを削除できます。セッションから全データを削除したければ、flushメソッドが使用できます。The forget method will remove a piece of data from the session. If you would like to remove all data from the session, you may use the flush method:

// 1キーを削除
$request->session()->forget('key');

// 複数キーを削除
$request->session()->forget(['key1', 'key2']);

$request->session()->flush();

セッションIDの再生成Regenerating The Session ID

セッションIDの再生成は多くの場合、悪意のあるユーザーからの、アプリケーションに対するsession fixation攻撃を防ぐために行います。Regenerating the session ID is often done in order to prevent malicious users from exploiting a session fixation[https://en.wikipedia.org/wiki/Session_fixation] attack on your application.

Laravelに組み込まれているLoginControllerを使用していれば、認証中にセッションIDは自動的に再生成されます。しかし、セッションIDを任意に再生成する必要があるのでしたら、regenerateメソッドを使ってください。Laravel automatically regenerates the session ID during authentication if you are using the built-in LoginController; however, if you need to manually regenerate the session ID, you may use the regenerate method.

$request->session()->regenerate();

カスタムセッションドライバの追加Adding Custom Session Drivers

ドライバの実装Implementing The Driver

カスタムセッションドライバでは、SessionHandlerInterfaceを実装してください。このインターフェイスには実装する必要のある、シンプルなメソッドが数個含まれています。MongoDBの実装をスタブしてみると、次のようになります。Your custom session driver should implement the SessionHandlerInterface. This interface contains just a few simple methods we need to implement. A stubbed MongoDB implementation looks something like this:

<?php

namespace App\Extensions;

class MongoSessionHandler implements \SessionHandlerInterface
{
    public function open($savePath, $sessionName) {}
    public function close() {}
    public function read($sessionId) {}
    public function write($sessionId, $data) {}
    public function destroy($sessionId) {}
    public function gc($lifetime) {}
}

lightbulb">Tip!! こうした拡張を含むディレクトリをLaravelでは用意していません。お好きな場所に設置してください。上記の例では、Extensionディレクトリを作成し、MongoSessionHandlerファイルを設置しています。{tip} Laravel does not ship with a directory to contain your extensions. You are free to place them anywhere you like. In this example, we have created an Extensions directory to house the MongoSessionHandler.

これらのメソッドの目的を読んだだけでは理解しづらいため、それぞれのメソッドを簡単に見てみましょう。Since the purpose of these methods is not readily understandable, let's quickly cover what each of the methods do:

- `open`メソッドは通常ファイルベースのセッション保存システムで使われます。Laravelは`file`セッションドライバを用意していますが、皆さんはこのメソッドに何も入れる必要はないでしょう。空のスタブのままで良いでしょう。実際、PHPが実装するように要求しているこのメソッドは、下手なインターフェイスデザインなのです。 - `close`メソッドも`open`と同様に通常は無視できます。ほどんどのドライバでは必要ありません。 - `read`メソッドは指定された`$sessionId`と紐付いたセッションデータの文字列バージョンを返します。取得や保存時にドライバ中でデータをシリアライズしたり、他のエンコード作業を行ったりする必要はありません。Laravelがシリアライズを行います。 - `write`メソッドはMongoDBやDynamoなどの持続可能なストレージに、`$sessionId`に紐付け指定した`$data`文字列を書き出します。ここでも、シリアリズを行う必要は全くありません。Laravelが既に処理しています。 - `destroy`メソッドは持続可能なストレージから`$sessionId`に紐付いたデータを取り除きます。 - `gc`メソッドは指定したUNIXタイムスタンプの`$lifetime`よりも古い前セッションデータを削除します。自前で破棄するMemcachedやRedisのようなシステムでは、このメソッドは空のままにしておきます。

ドライバの登録Registering The Driver

ドライバを実装したら、フレームワークへ登録する準備が整いました。Laravelのセッションバックエンドへドライバを追加するには、Sessionファサードextendメソッドを呼び出します。サービスプロバイダbootメソッドから、extendメソッドを呼び出してください。既存のAppServiceProviderか真新しく作成し、呼び出してください。Once your driver has been implemented, you are ready to register it with the framework. To add additional drivers to Laravel's session backend, you may use the extend method on the Session facade[/docs/{{version}}/facades]. You should call the extend method from the boot method of a service provider[/docs/{{version}}/providers]. You may do this from the existing AppServiceProvider or create an entirely new provider:

<?php

namespace App\Providers;

use App\Extensions\MongoSessionHandler;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\ServiceProvider;

class SessionServiceProvider extends ServiceProvider
{
    /**
     * コンテナ結合の登録
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * 全アプリケーションサービスの初期起動
     *
     * @return void
     */
    public function boot()
    {
        Session::extend('mongo', function ($app) {
            // Return implementation of SessionHandlerInterface...
            return new MongoSessionHandler;
        });
    }
}

セッションドライバを登録したら、config/session.php設定ファイルでmongoドライバが使用できます。Once the session driver has been registered, you may use the mongo driver in your config/session.php configuration file.

章選択

設定

明暗テーマ
light_mode
dark_mode
brightness_auto システム設定に合わせる
テーマ選択
photo_size_select_actual デフォルト
photo_size_select_actual モノクローム(白黒)
photo_size_select_actual Solarized風
photo_size_select_actual GitHub風(青ベース)
photo_size_select_actual Viva(黄緑ベース)
photo_size_select_actual Happy(紫ベース)
photo_size_select_actual Mint(緑ベース)
コードハイライトテーマ選択

明暗テーマごとに、コードハイライトのテーマを指定できます。

テーマ配色確認
スクリーン表示幅
640px
80%
90%
100%

768px以上の幅があるときのドキュメント部分表示幅です。

インデント
無し
1rem
2rem
3rem
原文確認
原文を全行表示
原文を一行ずつ表示
使用しない

※ 段落末のEボタンへカーソルオンで原文をPopupします。

Diff表示形式
色分けのみで区別
行頭の±で区別
削除線と追記で区別

※ [tl!…]形式の挿入削除行の表示形式です。

Pagination和文
ペジネーション
ペギネーション
ページネーション
ページ付け
Scaffold和文
スカフォールド
スキャフォールド
型枠生成
本文フォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

コードフォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

保存内容リセット

localStrageに保存してある設定項目をすべて削除し、デフォルト状態へ戻します。

ヘッダー項目移動

キーボード操作