LoginSignup
14
4

More than 3 years have passed since last update.

Laravel View表示におけるview()とredirect()の違いについて

Posted at

はじめに

ControllerやRouteからViewを展開する方法に
view()とredirect()をよく使いますが、その違いはなんでしょうか。
例えば

return view('profile.index')
return redirect('profile/index')

こちらはどちらも同じ結果を返します。
中身はどう違い、どういう原理で動いているのか、疑問に思ったので調べてみました。

view()

resources/viewsディレクトリに保存されているファイルを呼び出し相手のブラウザに表示させることができます。

例えば

resources/views/profile/index.blade.php
<html>
    <body>
        <h1>My name is kenji.</h1>
    </body>
</html>

上記、resources/views/profile/index.blade.phpという
Blade記法のファイルをRouteから直接呼び出し相手ブラウザに表示させたいときは

Route::get('profile/index', function () {
    return view('profile.index'); 
});

となり、https://~~/profile/indexにアクセスがあると
index.blade.phpがレンダリングされブラウザに表示されます。

redirect()

ユーザーを他のURLへリダイレクトさせることができます。

リダイレクトとは
別のページへ転送すること
出力先を本来のものから変えること
参照:https://wa3.i-3-i.info/word1482.html

redirect()は直接表示させたいViewを呼び出しているのではなく
RouteのGETリクエストからredirect()を介し
別のRouteのGETリクエストを通りViewを呼び出しています。
例えば


Route::get('test-redirect', function () {
    return redirect('profile/index');
});

    /*上記、redirect('profile/index')から
        下記、get引数の'profile/index'へ*/

Route::get('profile/index', function () {
    return view('profile.index'); 
});

https://~~/test-redirectにアクセスがあったとすると
redirect('profile/index')によってhttps://~~/profile/indexへアクセスを返し
view('profile.index')によってindex.blade.phpを表示させています。
この場合、イメージとしては2回Routeを通しています。
つまり、GETリクエストが2回行われていることになります。

まとめ

view()

RouteやControllerから直接ファイルを呼び出し、ブラウザへ表示させています。

redirect()

RouteやControllerから別のRouteへリクエストを出し、
そのRouteに沿ってViewを表示させています。

参照

公式:ビュー
https://readouble.com/laravel/5.5/ja/views.html
公式:レスポンス(リダイレクト)
https://readouble.com/laravel/5.5/ja/responses.html
※redirectはControllerアクションへリダイレクトすることもできたりと
他にも機能は様々です。詳しくは上記からお願いいたします。

最後までありがとうございます。
間違いご指摘ありましたら編集リクエストやコメントをしていただけると幸いです。

14
4
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
14
4