LoginSignup
12
15

More than 5 years have passed since last update.

Laravelのsessionの使い方

Last updated at Posted at 2016-05-28

Laravelには次のリクエストまで情報を一時保存できる session というものがある。
ちょいちょい使ってるのに「どういうときに使うのか」がよく分かってないのでまとめる。

流れ

  • flashメソッドでフォームデータをsessionに一時保存
  • 見つけたデータをリストに埋め込んで表示

flashメソッド

sessionに保存したデータは old で取得できる。

まずbladeに画面作成

actionに送信先url、methodに送信方法を。(もちろんpostでもOK)
oldを使ってリストにセッションのデータを埋め込めば、sessionに保存されたデータからほしいやつだけ取得できる。

<form action="url" method="get">
    <input type="text" id="name" name="name" placeholder="山田 太郎" >
    <button class="search" type="submit" value="検索">検索</button>
</form>


<thead>
    <tr>
        <th>名前</th>
    </tr>
</thead>
<tbody>
    <tr>
        <td>{{ old("name") }}</td>
    </tr>
</tbody>

ルート書く

Route::get('url', function(
    Request::flash();
    $name = Request::old('name');
    return view('index', [
        "name" => $name
    ]);
});

"検索"ボタンを押せばリストの {{ old("name"}} にnameの値が入るようになる。

追記

フォームの値を配列にして渡すことも可能。

form.blade.php
<input type="text" class="formItem__form" name="data[name_last]">
<input type="text" class="formItem__form" name="data[name_first]">

//lumen
$router->get("/confirm",function(Request $request){
    $request->flash();
    $data = $request->old('data');
    // dd($data);
    return view("confirm", [
    "form_data" => $data
]);

confirm.blade.php
    <p>{{$form_data["name_last"]}}</p>
    <p>{{$form_data["name_first"]}}</p>

dd()で返ってくる値

array:2 [▼
  "name_last" => "山田"
  "name_first" => "太郎"
]
12
15
1

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
15