【问题标题】:Session flash message executing two times Laravel会话闪存消息执行两次 Laravel
【发布时间】:2018-04-22 15:13:09
【问题描述】:

我的会话 Flash 消息有问题

我有这样一个简单的逻辑

if(empty($code))
        {
            return redirect()->back()->with('modal', 'working');
        }

在我的视图文件中,我正在为测试做警报

@if(session('modal'))
  <script>
    alert('working');
  </script>
@endif

问题是这个alert('working'); 被执行了两次。因此,当它重定向回来时,第一次是立即执行,第二次是在加载文档后执行。

我尝试了各种解决方法,例如删除会话密钥、加载准备好用于 javascript 的文档,但没有任何效果。

可能是什么问题?

【问题讨论】:

  • 您的 html 代码中可能有两次。你可以用浏览器检查html代码并检查你是否有两次?
  • 您能粘贴控制器和您遇到问题的刀片吗

标签: php laravel session laravel-5


【解决方案1】:

假设您正在使用引导程序...

这是我的处理方法:

在您的视图中创建一个名为:alerts 的新文件夹,并在其中创建一个名为 alerts.blade.php 的文件

粘贴:

@if (Session::has('success'))
    <div class="alert alert-success alert-dismissable">
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
        {{ Session::get('success') }}
    </div>
@elseif (Session::has('error'))
    <div class="alert alert-danger">
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
        {{ Session::get('error') }}
    </div>
@elseif(Session::has('warning'))
    <div class="alert alert-warning">
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
        {{ Session::get('warning') }}
    </div>
@endif

在您拥有的每个文件中,您现在可以使用:include('alerts.alerts')

现在在您的控制器中,如果您希望标记错误/警告或成功消息,只需使用:

Session::flash('success', 'Success message here')

return redirect()->back();


Session::flash('error', 'Error message here')

return redirect()->back();


Session::flash('warning', 'warning message here')

return redirect()->back();

这样您就不必一直向每个包含任何类型消息的页面添加 HTML,因为您只需包含一个在调用时会标记的文件。

我知道最初的化妆似乎有点冗长,但最终它会为你节省很多时间

【讨论】:

    【解决方案2】:

    你应该像这样使用 laravel flash helper,

    $request-&gt;session()-&gt;flash('status', 'Task was successful!');

    return back();

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-14
      • 2021-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-19
      • 1970-01-01
      • 2017-06-09
      相关资源
      最近更新 更多