I\'m making my first app in Laravel and am trying to get my head around the session flash messages. As far as I\'m aware in my controller action I can set a flash message ei
For my application i made a helper function:
function message( $message , $status = 'success', $redirectPath = null )
{
$redirectPath = $redirectPath == null ? back() : redirect( $redirectPath );
return $redirectPath->with([
'message' => $message,
'status' => $status,
]);
}
message layout, main.layouts.message
:
@if($status)
<div class="center-block affix alert alert-{{$status}}">
<i class="fa fa-{{ $status == 'success' ? 'check' : $status}}"></i>
<span>
{{ $message }}
</span>
</div>
@endif
and import every where to show message:
@include('main.layouts.message', [
'status' => session('status'),
'message' => session('message'),
])
In your view:
<div class="flash-message">
@foreach (['danger', 'warning', 'success', 'info'] as $msg)
@if(Session::has('alert-' . $msg))
<p class="alert alert-{{ $msg }}">{{ Session::get('alert-' . $msg) }}</p>
@endif
@endforeach
</div>
Then set a flash message in the controller:
Session::flash('alert-danger', 'danger');
Session::flash('alert-warning', 'warning');
Session::flash('alert-success', 'success');
Session::flash('alert-info', 'info');
Simply return with the 'flag' that you want to be treated without using any additional user function. The Controller:
return \Redirect::back()->withSuccess( 'Message you want show in View' );
Notice that I used the 'Success' flag.
The View:
@if( Session::has( 'success' ))
{{ Session::get( 'success' ) }}
@elseif( Session::has( 'warning' ))
{{ Session::get( 'warning' ) }} <!-- here to 'withWarning()' -->
@endif
Yes, it really works!
Another solution would be to create a helper class How to Create helper classes here
class Helper{
public static function format_message($message,$type)
{
return '<p class="alert alert-'.$type.'">'.$message.'</p>'
}
}
Then you can do this.
Redirect::to('users/login')->with('message', Helper::format_message('A bla blah occured','error'));
or
Redirect::to('users/login')->with('message', Helper::format_message('Thanks for registering!','info'));
and in your view
@if(Session::has('message'))
{{Session::get('message')}}
@endif
I think the following would work well with lesser line of codes.
session()->flash('toast', [
'status' => 'success',
'body' => 'Body',
'topic' => 'Success']
);
I'm using a toaster package, but you can have something like this in your view.
toastr.{{session('toast.status')}}(
'{{session('toast.body')}}',
'{{session('toast.topic')}}'
);
You can make a multiple messages and with different types. Follow these steps below:
app/Components/FlashMessages.php
"namespace App\Components; trait FlashMessages { protected static function message($level = 'info', $message = null) { if (session()->has('messages')) { $messages = session()->pull('messages'); } $messages[] = $message = ['level' => $level, 'message' => $message]; session()->flash('messages', $messages); return $message; } protected static function messages() { return self::hasMessages() ? session()->pull('messages') : []; } protected static function hasMessages() { return session()->has('messages'); } protected static function success($message) { return self::message('success', $message); } protected static function info($message) { return self::message('info', $message); } protected static function warning($message) { return self::message('warning', $message); } protected static function danger($message) { return self::message('danger', $message); } }
app/Http/Controllers/Controller.php
".namespace App\Http\Controllers; use Illuminate\Foundation\Bus\DispatchesJobs; use Illuminate\Routing\Controller as BaseController; use Illuminate\Foundation\Validation\ValidatesRequests; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Illuminate\Foundation\Auth\Access\AuthorizesResources; use App\Components\FlashMessages; class Controller extends BaseController { use AuthorizesRequests, AuthorizesResources, DispatchesJobs, ValidatesRequests; use FlashMessages; }
This will make the FlashMessages
trait available to all controllers that extending this class.
views/partials/messages.blade.php
"@if (count($messages)) <div class="row"> <div class="col-md-12"> @foreach ($messages as $message) <div class="alert alert-{{ $message['level'] }}">{!! $message['message'] !!}</div> @endforeach </div> </div> @endif
boot()
" method of "app/Providers/AppServiceProvider.php
":namespace App\Providers; use Illuminate\Support\ServiceProvider; use App\Components\FlashMessages; class AppServiceProvider extends ServiceProvider { use FlashMessages; public function boot() { view()->composer('partials.messages', function ($view) { $messages = self::messages(); return $view->with('messages', $messages); }); } ... }
This will make the $messages
variable available to "views/partials/message.blade.php
" template whenever it is called.
views/partials/messages.blade.php
"<div class="row"> <p>Page title goes here</p> </div> @include ('partials.messages') <div class="row"> <div class="col-md-12"> Page content goes here </div> </div>
You only need to include the messages template wherever you want to display the messages on your page.
use App\Components\FlashMessages; class ProductsController { use FlashMessages; public function store(Request $request) { self::message('info', 'Just a plain message.'); self::message('success', 'Item has been added.'); self::message('warning', 'Service is currently under maintenance.'); self::message('danger', 'An unknown error occured.'); //or self::info('Just a plain message.'); self::success('Item has been added.'); self::warning('Service is currently under maintenance.'); self::danger('An unknown error occured.'); } ...
Hope it'l help you.