LoginSignup
67
54

More than 3 years have passed since last update.

【Laravel】リダイレクトの書き方メモ

Last updated at Posted at 2020-11-15
  • リダイレクト定義の書き方について。
リダイレクトの基本
// httpの場合
return redirect('test/index');                 // http://xxxxx/test/index
return redirect()->to('test/index');           // ↑と同義
return redirect('test/index', 301);            // ステータスコードを指定する場合(※ デフォルトは、302)
return redirect('test/index', 301, ['test-header' => 'テスト'] ); // HTTPヘッダー を追加する場合

// httpsの場合
return redirect('test/index', 302, [], true);  // https://xxxxx/test/index


// ルート名での指定
return redirect()->route('test.list');
return redirect()->route('test.show', ['id' => 12]);      // id情報を含むルーティングの場合(例: test/{id} )
$user = App\User::find(12);                               // ↑と同義
return redirect()->route('test.show', ['id' => $test]);


// コントローラ名での指定
return redirect()->action('TestController@index');
return redirect()->action('TestController@show', ['id' => 12]);    // id情報を含む場合

パス、アクションの指定

パス、アクションの指定
return redirect($to = null, $status = 302, $headers = [], $secure = null);          // パスの指定
return redirect()->to($path, $status = 302, $headers = [], $secure = null);         // 取得インスタンスへのパス指定
return redirect()->route($route, $parameters = [], $status = 302, $headers = []);   // 取得インスタンスへのルート指定
return redirect()->action($action, $parameters = [], $status = 302, $headers = []); // 取得したインスタンスへアクション指定
return redirect()->away($path, $status = 302, $headers = []);                       // 取得したインスタンスへの外部ドメインの指定

// コントローラを使わず、リダイレクト先を指定する場合
Route::redirect($uri, $destination, $status = 301);

データも一緒にリダイレクト

セッションデータと一緒にリダイレクト(※フラッシュメッセージなどに使う)
return redirect('home')->with('result', '完了');
return redirect('home')->with([       // 複数データを格納する場合は、配列で!
    'result_1'=>'成功-1', 'result_2'=>'成功-2', 'result_3'=>'成功-3'
]);
// ビューで取得
{{ session('result') }}

直前ページへのリダイレクト

直前ページにリダイレクト
// 基本
public function back() {
    return back();
}

// データも一緒に、直前ページに戻す場合
public function back() {
    return back()->with('result', 'ok!');
    return back()->withInput();     // 送信データがセッション内に格納される
}
// ビューで取得
{{ session('result') }}

// 例
public function back(Request $request) {
    return back()->withInput($request->only(['email']));
}
// ビューで取得
<textarea name="message">{{ old('message') }}</textarea>
67
54
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
67
54