LoginSignup
7
11

More than 5 years have passed since last update.

return redirect('hogehoge')->with('message','ってかいたらいつでもメッセージだしたい');

Last updated at Posted at 2016-04-18

リダイレクトするときにメッセージを

ログインが必要なときはログインに自動的にリダイレクトして
リダイレクトされた理由をメッセージ出したかったので、そこら辺のコードをコピペしたのですが、messageを出力するところをコピペしておらず困りました。

レイアウト(layout)に書いておくと便利だったので、メモします。

コントローラ

app/Http/Controllers/PostController.php
//省略

class PostController extends Controller
{
    // 省略
    public function create()
    {
        if (Gate::denies('create', $this->post)) {
            return redirect('login')->with('message', '投稿するにはログインしてください。');
        }
        return view('post.create');
    }
    // 省略
}

レイアウト

resources/views/layouts/app.blade.php

// 良き場所に適当に

@if (session('message'))
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <div class="alert alert-warning">
                {{ session('message') }}
            </div>
        </div>
    </div>
    @endif
@yield('content')

公式のマニュアル

公式のマニュアルではこのような場所に書いてありました。
英語読めないと探すのが辛いね。

Session - Laravel - The PHP Framework For Web Artisans Redirecting With Flashed Session Data
https://laravel.com/docs/5.1/responses#redirecting-with-flashed-session-data

おまけ

ついでですが、controllerredirectはヘルパーメソッドでこんな風に定義されています。

vendor/laravel/framework/src/Illuminate/Foundation/helpers.php
if (! function_exists('redirect')) {
    /**
     * Get an instance of the redirector.
     *
     * @param  string|null  $to
     * @param  int     $status
     * @param  array   $headers
     * @param  bool    $secure
     * @return \Illuminate\Routing\Redirector|\Illuminate\Http\RedirectResponse
     */
    function redirect($to = null, $status = 302, $headers = [], $secure = null)
    {
        if (is_null($to)) {
            return app('redirect');
        }

        return app('redirect')->to($to, $status, $headers, $secure);
    }
}

そして、redirectが返すのは、RedirectResponseのインスタンスで、このクラスのwithでは、渡したKeyとValueが、Session::flashとされています。(flashは一回きりのセッションデータだよって意味)

vendor/laravel/framework/src/Illuminate/Http/RedirectResponse.php
/**
 * Flash a piece of data to the session.
 *
 * @param  string|array  $key
 * @param  mixed  $value
 * @return \Illuminate\Http\RedirectResponse
 */
public function with($key, $value = null)
{
    $key = is_array($key) ? $key : [$key => $value];

    foreach ($key as $k => $v) {
        $this->session->flash($k, $v);
    }

    return $this;
}
7
11
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
7
11