Laravel 5.2 - Session flash data not set in service provider

时间:2016-08-31 17:26:14

标签: laravel laravel-5 laravel-5.2

I have created a frontend service provider for my app:

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Session;

class FrontendServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        view()->share('message', !is_null(Session::get('message')) ? '<div class="alert alert-success"><strong>Success! </strong>'.Session::get('message').'</div>' : '');
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

I am setting a flash message in the controller like so:

public function resend_welcome($token)
{
    $user_id = Crypt::decrypt($token);
    $user = User::findOrFail($user_id);
    if($user->meta->confirmed==1) {
        abort(404);
    }
    Event::fire(new UserRegistered($user));

    Session::flash('message', 'A new email has been sent.');

    return redirect(route('register.success', $token));
}

Then in my view I am trying to output $message like so:

{{ $message }}

The problem is $message is always NULL. If I use Session::get('message') in my view instead then it works and the flash message is displayed. Why is Session::get('message') always NULL in the service provider even though I have set it in the controller?

1 个答案:

答案 0 :(得分:1)

In Laravel 5 accessing session information inside a service provider boot method is not possible as the session logic is only started as part of the web middleware group Illuminate\Session\Middleware\StartSession::class.

To share the view variable you can use Middleware for that. Something like:

class BroadcastFlashMessage
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure                 $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        view()->share('message', !is_null(Session::get('message')) 
            ? '<div class="alert alert-success"><strong>Success! </strong>'.Session::get('message').'</div>' 
            : '');

        return $next($request);
    }
}

An alternative is to use laracasts/flash package.