Laravel会话flash消息在回页时出现多次


Laravel session flash message appears multiple times on pageback

在我的控制器中:

 Session::flash('created', "Student created");
 return Redirect::to('student');

在我看来:

 @if(Session::has('created'))
 alert('updated');
 @endif

对于我来说,我使用Session::pull('key')而不是Session::get('key'),它只弹出一次。

@if(Session::has('success'))
    {{ Session::pull('success') }} 
@endif  

根据Laravel 7。x医生

pull方法将在一条语句中从会话中检索和删除一个项:

显示会话消息

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

从控制器

调用
return redirect()->back()->with('success', 'Data added successfully');

请避免不必要的使用session。你可以使用Redirect::route。检查下面的例子:

1)将$strChecked = false;初始化为学生路由控制器,然后将$strChecked = true;初始化为学生更新方法。

2)将返回行替换为return 'Redirect::route('student')->with('strChecked', $strChecked);

3)然后在你的视图中,你可以使用:
@if($strChecked)
    alert('updated');
@endif

编辑:

让我用我的工作演示代码来说明:

1)路线:

Route::get('flash', 'FlashController@flashIndex')->name('frontend.flash');
Route::post('flash/update', 'FlashController@studentUpdate')->name('frontend.flash.update');

2)观点:

@section('content')
{{ Form::open(['route' => 'frontend.flash.update', 'class' => 'form-horizontal']) }}
{{ Form::submit('Demo', ['class' => 'btn btn-primary', 'style' => 'margin-right:15px']) }}  
{{ Form::close() }}
@endsection
@section('after-scripts-end')
    <script>
        @if(Session::has('created'))
         alert('updated');
        @endif
    </script>
@stop

3)控制器:

//Method to display action...
public function flashIndex()
{
 return view('frontend.flash');  
}
//Method to update action...
public function studentUpdate()
{
 Session::flash('created', "Student created");
 return Redirect::to('flash'); 
}

希望这能消除你的疑虑。

上面的例子在我的结束工作良好。如果不适合您,请描述您的代码。