10
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【laravel】リダイレクト処理

Posted at

概要

laravelのリダイレクト機能について簡単な備忘録を投稿します。
何気なく使用しているredirect関数ですが細かく分類すると3つの使い方に分類できます。
・PHPのheader関数のように指定したパスを表示する
Illuminate\Http\RedirectResponseクラスのインスタンス
Illuminate\routing\Redirectorクラスのインスタンス

また、redirectメソッドはグローバルに使用できるヘルパー関数の一つで、どのクラスにおいても自由に使える関数です。

RedirectResponseクラス

Illuminate\Http\RedirectResponseクラスのレスポンスを返すredirectメソッドです。
ここではthis自身をreturnするシンプルなメソッドをまとめます。

内容 メソッド 概要
入力データの付加 $response->withInput() 送信されたフォームの値をInput::old()へ引き継ぐ
バリデーションのエラーを付加する $response->withError() 引数の値を$errors変数へ保存してリダイレクト先へ引き継ぐ
クッキーを付加する $response->WithCookie() クッキーを保存してリダイレクト先へ引き継ぐ

Redirecorクラス

引数をなしで呼び出すとIlluminate\routing\Redirectorクラスのインスタンスが返されます。
主にルーティングに関する情報を扱う機能です。

内容 メソッド 概要
ルートの指定 redirect()->route('ルート名','配列') web.phpにルート情報として記述したものを指定します。
アクションの指定 redirect()->action('アクションの指定','配列') SampleController@indexのようにコントローラーにアクションを指定します。
ビューを指定 redirect()->view('ビュー名') ビューを指定してリダイレクトします。
JSONにデータを返す redirect()->json('テキスト') JSONデータっをクライアントに返します。
ファイルを表示 redirect()->file('ファイルパス') パスで指定したファイルを表示します。
ファイルをダウンロード redirect()->download('ファイルパス') パスで指定したファイルをダウンロードします。

参考

[ヘルパ(redirect)]
(https://readouble.com/laravel/6.x/ja/helpers.html#method-redirect)
[HTTPレスポンス]
(https://readouble.com/laravel/6.x/ja/responses.html#redirects)

10
9
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
10
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?