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() / compact() の違いを理解する

Last updated at Posted at 2025-03-24

はじめに

Laravelのコントローラでビューを返すとき、必ず使うのが return view()
よく見るけど、「第1引数? 第2引数? 第3引数?」「with() と compact() ってどう違うの?」と迷ったことはありませんか?

この記事では、view() の引数の意味と、with()compact() の使い方の違いを初心者向けに整理してみました。


return view() の基本構文

Laravelの view() 関数は以下のように3つの引数を取ることができます:

return view($view, $data = [], $mergeData = []);

IMG_3739.jpeg

使用例

 return view('posts.index', ['title' => '記事一覧'], ['user' => $user]);

この例では、posts/index.blade.php に以下の変数が渡されます:

  • $title → '記事一覧'
  • $user → $userオブジェクト(第3引数が上書きされる)

②with() メソッドの使い方

view() の戻り値に対してチェーンで使えるメソッドです。

return view('posts.index')->with('title', '記事一覧');

複数渡すとき:

return view('posts.index')
    ->with('title', '記事一覧')
    ->with('user', $user);
  • 可読性はやや下がるが、個別に追加しやすい
  • 条件分岐の中で追加する場合にも便利

③compact() 関数の使い方

PHP標準の関数で、変数名をそのままキーとした連想配列を作成できます。

$title = '記事一覧';
$user = Auth::user();

return view('posts.index', compact('title', 'user'));

上記は実質以下と同じ意味になります:

return view('posts.index', ['title' => $title, 'user' => $user]);
  • コードがスッキリして読みやすい
  • 複数の変数をまとめて渡したいときに便利

④with() と compact() の違いまとめ

IMG_3740.jpeg

⑤まとめ

  • return view() の 第1引数:ビューのパス
  • 第2引数:ビューに渡す変数の配列
  • 第3引数:追加で上書きしたい変数(あまり使わない)
    そして、
  • compact():複数変数をまとめて渡すときに便利(コードが短くなる)
  • with():チェーン形式で個別に変数を渡したいときに便利(条件分岐にも強い)
    どちらを使っても結果は同じなので、チームのコーディングスタイルや可読性のバランスで使い分けると良いでしょう!
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?