Laravel - 在会话和测试之后显示警报的最佳实践
Laravel - Best Practices To Display Alert with Session & Test After
我和 Laravel 一起开发在线软件已经一个月了。
执行操作(更新、创建等)时,我会向用户显示一条信息消息。
在我的控制器中像这样:
$request->session()->flash('alert', array(array('msg' => 'My first alert message', 'level' => 'success')));
$request->session()->push('alert', array('msg' => "My second message", 'level' => 'danger'));
在我看来:
@if(Session::has('alert'))
@foreach(Session::get('alert') as $alert)
<div class="alert alert-{{ $alert['level'] ?? 'info' }} alert-dismissible fade show">
<button type="button" class="close" data-dismiss="alert">×</button>
{{ $alert['msg'] }}
</div>
@endforeach
@endif
到此为止,我经常使用这个逻辑。
我碰巧在我的应用程序中创建了测试(我使用 Pest PHP),当我想在我的控制器中测试一个包含会话的函数时,我得到了这个错误:
• TestsControllersExchangesTest > it update exchange
RuntimeException
Session store not set on request.
事实上,在我的测试中,我模拟了一个错误的函数请求(例如更新),但是当需要在请求中闪现会话消息时,它 returns 上面的错误。
能否在请求中插入一个虚假的session(网上找不到成功的人)?
或者我应该更改我的警报系统(这可能不符合最佳实践)?
感谢您的帮助
您可以使用 Facade 方法 Session :
Session::flash('alert', 'success|Notification text');
还有你 blade 提醒:
@if(Session::has('alert'))
<div class="alert alert-{{ explode('|', Session::get('alert'))[0] ?? 'info' }} alert-dismissible fade show">
<button type="button" class="close" data-dismiss="alert">×</button>
{{ explode('|', Session::get('alert'))[1] }}
</div>
@endif
测试中的 session 不再有任何问题。
您可以简单地模拟您的请求而无需 session。
我和 Laravel 一起开发在线软件已经一个月了。 执行操作(更新、创建等)时,我会向用户显示一条信息消息。
在我的控制器中像这样:
$request->session()->flash('alert', array(array('msg' => 'My first alert message', 'level' => 'success')));
$request->session()->push('alert', array('msg' => "My second message", 'level' => 'danger'));
在我看来:
@if(Session::has('alert'))
@foreach(Session::get('alert') as $alert)
<div class="alert alert-{{ $alert['level'] ?? 'info' }} alert-dismissible fade show">
<button type="button" class="close" data-dismiss="alert">×</button>
{{ $alert['msg'] }}
</div>
@endforeach
@endif
到此为止,我经常使用这个逻辑。
我碰巧在我的应用程序中创建了测试(我使用 Pest PHP),当我想在我的控制器中测试一个包含会话的函数时,我得到了这个错误:
• TestsControllersExchangesTest > it update exchange
RuntimeException
Session store not set on request.
事实上,在我的测试中,我模拟了一个错误的函数请求(例如更新),但是当需要在请求中闪现会话消息时,它 returns 上面的错误。
能否在请求中插入一个虚假的session(网上找不到成功的人)?
或者我应该更改我的警报系统(这可能不符合最佳实践)?
感谢您的帮助
您可以使用 Facade 方法 Session :
Session::flash('alert', 'success|Notification text');
还有你 blade 提醒:
@if(Session::has('alert'))
<div class="alert alert-{{ explode('|', Session::get('alert'))[0] ?? 'info' }} alert-dismissible fade show">
<button type="button" class="close" data-dismiss="alert">×</button>
{{ explode('|', Session::get('alert'))[1] }}
</div>
@endif
测试中的 session 不再有任何问题。 您可以简单地模拟您的请求而无需 session。