LoginSignup
4
0

More than 3 years have passed since last update.

Laravel 値を持たせてリダイレクトさせる

Last updated at Posted at 2020-05-05

目的

  • 値を持たせた状態でリダイレクトを行う方法をまとめる

実施環境

  • ハードウェア環境
項目 情報
OS macOS Catalina(10.15.3)
ハードウェア MacBook Pro (16-inch ,2019)
プロセッサ 2.6 GHz 6コアIntel Core i7
メモリ 16 GB 2667 MHz DDR4
グラフィックス AMD Radeon Pro 5300M 4 GB Intel UHD Graphics 630 1536 MB
  • ソフトウェア環境
項目 情報 備考
PHP バージョン 7.4.3 Homwbrewを用いて導入
Laravel バージョン 7.0.8 commposerを用いて導入
MySQLバージョン 8.0.19 for osx10.13 on x86_64 Homwbrewを用いて導入

前提情報

  • とあるアプリのFooControllerに下記のような記載があるとする。

    public function index() {
        return redirect('/user_home');
    }
    
    public function user_home() {
        return view('home.user_home');
    }
    
  • ルーティングファイルには下記の内容が記載されているものとする。

    web.php
    Route::get('/user_home', FooController@user_home);
    
  • indexアクションが読み込まれると/user_homeにリダイレクト→ルーティングの記載によりuser_homeアクションに入る→homeディレクトリにあるuser_home.blade.phpがビューとして出力されると言う流れである。

具体例

  • indexアクション内で連想配列$stringsを定義して値を格納する。
  • 連想配列$stringsをリダイレクト先のuser_homeアクションで受け取り、連想配列$redirect_stringsに格納する方法を下記に記載する。
  • 下記にFooControllerの内容を記載する。

    public function index() {
        //変数の定義
        $strings = [
             'str_1' => 'test1',
             'str_2' => 'test2',
             'str_3' => 'test3',
        ]
        return redirect('/user_home')->withInput($strings);
    }
                             //値を受け取るので下記にRequestを記載する
    public function user_home(Request $request) {
        //redirect時の$stringsの値は$requestのoldに格納されている。
        //値を取り出して連想配列に格納する。
        $redirect_strings = [
            'redirect_str_1' => $request->old('str_1'),
            'redirect_str_2' => $request->old('str_2'),
            'redirect_str_3' => $request->old('str_3'),
        ]
        return view('home.user_home');
    }
    

参考文献

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