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?

return view()->withの使い方を少し深ぼってみる

Last updated at Posted at 2025-03-26

はじめに

Laravelでビュー(Bladeテンプレート)に変数を渡す際、よく使われるのがこの書き方:

return view('sample')->with('title', '記事一覧');

最初のうちは「これ、どうやって渡してるの?」「Blade側でどう受け取るんだ?」と疑問に感じる部分ではあります。

この記事では、view()->with()の仕組みと、Blade側での参照方法を、軽く深堀していきます!

①view()->with()の基本構文

return view('viewファイル名')->with('キー',);
  • 'キー'はBlade側で使う変数名になります。
    - 値は任意のデータ(文字列、配列、オブジェクトなど)

例:

return view('posts.index')->with('titile', '投稿一覧');

この場合、Bladeテンプレートresources/view/posts/index.blade.phpに$titleという変数が渡されます。

②Blade(View)側での参照方法

Blade側では、with()の第一引数がそのまま変数名として使えるようになります。

<h1>{{ $title }}</h1>

このように、コントローラでwith('title', '投稿一覧')と書けば、Blade側では{{ $title }}で表示できます。

③実務での複数データ渡し(チェーンで渡す)

return view('posts.index')
     ->with('title', '投稿一覧')
     ->with('user', $user)
     ->with('count', 5);

Blade側:

<h1>{{ $title }}</h1>
<p>{{ $user->name }}</p>
<p>{{ $count }}</p>

④データ構造を理解する(裏側では配列に変換されている)

実はwtith()は内部的には$data配列にキーと値を追加しているだけです。

以下のコードと全く同じ結果になります。

return view('posts.index', [
    'title' => '投稿一覧',
    'user' => $user,
    'count' => 5,
]);

つまり、with() は「見た目がチェーンメソッドになっているだけ で、やっていることは同じです。

⑤いつwith()を使うのか?

IMG_7730.jpeg

⑥条件分岐との組み合わせ例(応用)

$view = view('dashboard')->with('user', $user);

if ($user->is_admin) {
    $view->with('admin_message', 'ようこそ管理者様');
}

return $view;

Blade側:

<h1>{{ $user->name }}さん、こんにちは</h1>

@if(isset($admin_message))
    <p>{{ $admin_message }}</p>
@endif
  • このようにwith()は後から動的に追加できるのが強みです。

⑦まとめ

IMG_7731.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?