Showing a message bar is very common task in writing PHP apps. In Laravel, there is even a built-in command ‘with
’ to show a message bar with easy!
For example:
return redirect('/')->with('success', 'It works!');
However, this message bar shows green color only, which utilize class="alert alert-success"
with Bootstrap 4 Alerts.
Multiple types of alerts
There are eight types of alerts with different colors which can be classified as different usage. For example, the message with green color means a successful operation, while the one with red color often suggests a dangerous or fail situation.
<div class="alert alert-primary" role="alert">
This is a primary alert—check it out!
</div>
<div class="alert alert-secondary" role="alert">
This is a secondary alert—check it out!
</div>
<div class="alert alert-success" role="alert">
This is a success alert—check it out!
</div>
<div class="alert alert-danger" role="alert">
This is a danger alert—check it out!
</div>
<div class="alert alert-warning" role="alert">
This is a warning alert—check it out!
</div>
<div class="alert alert-info" role="alert">
This is a info alert—check it out!
</div>
<div class="alert alert-light" role="alert">
This is a light alert—check it out!
</div>
<div class="alert alert-dark" role="alert">
This is a dark alert—check it out!
</div>
The code
Let’s modify the code of message bar in order to show different types of alert.
Before
<div class="uper">
@if(session()->get('success'))
<div class="alert alert-success">
<button type="button" class="close"
data- dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
{{ session()->get('success') }}
</div><br/>
@endif
</div>
After
<div class="uper">
@if(session('message'))
<div class="alert alert-{{ session('message')[0] }}" >
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
{{ session('message')[1] }}
</div>
@endif
</div>
Usage:
return redirect('/')
->with('message', ['danger', 'You are not an authorized user!']);
The session key is set to ‘message’ and the value is an array which contains ‘message type’ and ‘message content’.
That’s all!
No comments:
Post a Comment