0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Laravelの session()->flash() と view() の違いを整理してみた【一時データ vs ビュー描画の本質】

Posted at

はじめに

Laravelでよく使う関数やメソッドに、

  • session()->flash('key', 'value')
  • return view('viewname', [...])

があります。

一見、全く違う用途に思えますが、「データをどこかに一時的に渡す」という点では共通点もあります。

この記事では、flash() の意味と使い方、view() との違いや使い分けについて、整理してみました。


session()->flash() とは?

意味:

Laravelのセッションに「1回限りの一時データ」を保存するためのメソッドです。

session()->flash('message', '投稿が完了しました!');

特徴:

  • 次のリクエストで1度だけ取り出せる
  • 表示された後は自動で削除される
  • 通常は redirect() と一緒に使う

使用例:

public function store(Request $request)
{
    // 保存処理...
    session()->flash('message', '保存しました!');
    return redirect()->route('posts.index');
}

Blade側:

@if (session('message'))
    <div class="alert alert-success">
        {{ session('message') }}
    </div>
@endif

→投稿一覧画面にリダイレクト後、「保存しました!」という1回限りのメッセージが表示される

②view() 関数とは?

意味:
特定の Blade テンプレート(ビュー)を表示する関数。コントローラーやルートでよく使います。

return view('posts.index', ['posts' => $allPosts]);

特徴:

  • ビューに変数をその場で直接渡す
  • セッションやリダイレクトを挟まず、即時に表示

使用例:

public function index()
{
    $posts = Post::all();
    return view('posts.index', ['posts' => $posts]);
}

Blade側:

@foreach ($posts as $post)
    <p>{{ $post->title }}</p>
@endforeach

③共通点と違い

IMG_7754.jpeg

④おまけ:redirect()->with() との違いは?

実は with() は flash() のショートカットです:

return redirect()->route('home')->with('message', 'ようこそ!');

これは内部的に:

session()->flash('message', 'ようこそ!');

と同じ処理をしています。

⑤まとめ

IMG_7755.jpeg

「データを一時的に渡す」のか、「今すぐ描画に使う」のかを意識すると、両者の違いがスッキリ理解できます。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?