1
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?

More than 1 year has passed since last update.

Laravelでリダイレクト処理を書く方法

Last updated at Posted at 2023-06-18

Laravelでリダイレクト処理を書く方法

コントローラ内のメソッドに返り値として記述する。

〇〇Controller.php
class 〇〇Controller extends Controller
{
	// リダイレクト
	public function redirect() {
		return redirect('URL');
	}
}

・リダイレクトはredirect()関数を使用する。
 これはどのディレクトリからも自由にアクセスできる関数。
・redirect関数の書き方は以下の通り。route()メソッドを使用するのがおすすめ。(URLの変更にも影響を受けないため)

// URLを直接指定する
return redirect('URL');

// to()メソッドを使ってURLを直接指定する
return redirect()->to('URL');

// route()ヘルパーを使って名前付きルートを指定する
return redirect(route('ルート名'));

// route()メソッドを使って名前付きルートを指定する ★おすすめ
// 補足:route()ヘルパーとは異なる。redirect()ヘルパーは引数が空だとRedirectorというクラスのインスタンスを返すが、そのインスタンスが持つroute()メソッドのこと
return redirect()->route('ルート名');

// action()メソッドを使ってコントローラとアクションを指定する
return redirect()->action([コントローラ名::class, 'アクション名']);

リダイレクトした後、フラッシュメッセージを表示したい場合

〇〇Controller.php
class 〇〇Controller extends Controller
{
	// リダイレクト
	public function redirect() {
		return redirect()->route('ルート名')->with('キー名', '任意のメッセージ');
	}
}

・フラッシュメッセージ:処理結果をユーザーに伝えるためのメッセージ。
・with('キー名','任意のメッセージ'):
 フラッシュメッセージを表示するための関数。
 セッション($_session('キー名'))にメッセージが保存される仕組み。
image.png

1
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
1
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?