PHP Laravel会话Flash警报消息未显示

ST8*_*T80 5 php laravel

在我的laravel-app中,用户可以订阅通讯录上的复选框。选中复选框并提交表单后,控制器中会进行检查,如果用户已被订阅,如果已订阅,则将显示一个闪烁的警报/消息,并带有“您已被订阅”之类的信息。现在,检查本身可以工作,但是没有显示Flash / Alert消息,我也不知道为什么。

在我看来:

@if (\Session::has('success'))
    <div class="alert alert-success">
       <p>{{ \Session::get('success') }}</p>
    </div>
@endif
@if (\Session::has('failure'))
    <div class="alert alert-danger">
       <p>{{ \Session::get('failure') }}</p>
    </div>
@endif
 <div class="contact-form" id="contact">
     <form method="POST" action="{{ route('contact.store') }}">
     ...
     </form>
 </div>
Run Code Online (Sandbox Code Playgroud)

在我的控制器中:

// when the checkbox is checked!

if (!empty(request()->newsletter)) {
    if (!Newsletter::isSubscribed(request()->email)) {
        Newsletter::subscribePending(request()->email);

        return redirect()->route('contact.create')->with('success', 'Thanks for subscribing!');

    } else {

        return redirect()->route('contact.create')->with('failure', 'You are already subscribed');

    }
}
Run Code Online (Sandbox Code Playgroud)

有人可以帮我吗?

Tim*_*lvy 6

您似乎正在使用会话类,而不是会话帮助程序laravel插入服务容器。

如果您使用的是Laravel 5.8,根据此处的文档,blade中的session是一个辅助函数:

https://laravel.com/docs/5.8/responses#redirecting-with-flashed-session-data

一个例子

Route::post('user/profile', function () {
    // Update the user's profile...

    return redirect('dashboard')->with('status', 'Profile updated!');
});
Run Code Online (Sandbox Code Playgroud)

因此,像这样在blade中使用helper函数:

@if (session('status'))
    <div class="alert alert-success">
        {{ session('status') }}
    </div>
@endif
Run Code Online (Sandbox Code Playgroud)

注意:这仅在使用页面提交时才有效。如果是javascript提交,则可能需要刷新页面以显示警报。

  • 不幸的是,这不起作用:-/ (2认同)