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?
答案 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.