Skip to content

Instantly share code, notes, and snippets.

@Ellrion
Last active March 5, 2018 15:04
Show Gist options
  • Save Ellrion/7ee8085b35f0de8c6d386255f9dd16bb to your computer and use it in GitHub Desktop.
Save Ellrion/7ee8085b35f0de8c6d386255f9dd16bb to your computer and use it in GitHub Desktop.
Flash messages min service for Laravel (only backend)

Simple use

In Controllers:

  flash('Some info message');
  flash()->error('This is some error!')
  //flash()->warning
  //flash()->success
  //flash()->info

In Template:

  @foreach(flash()->messages() as $message)
    <div>{{ $message->level }}: {{ $message->text }}</div>
  @endforeach

Or only one message level:

  @foreach(flash()->messages('danger') as $message)
    <div class="alert-danger">{{ $message->text }}</div>
  @endforeach
  @foreach($errors->all() as $message)
    <div class="alert-danger">{{ $message }}</div>
  @endforeach

Multiple messages

  flash()->warning('Warning One');
  flash()->warning('Warning Two');
  flash()->success('But we did it')

Extra data for messages

And possible add some extra data with message:

  flash()->error('This error show in modal', ['important' => true])

and read it in view

  @foreach(flash()->messages() as $message)
    <div class="message" @if(!empty($message->important)) data-modal="" @endif>
      {{ $message->text }}
    </div>
  @endforeach
<?php
namespace App\Services\Foundation;
use Illuminate\Session\Store;
use Illuminate\Support\Collection;
/**
* Register it in AppServiceProvider (or other): $this->app->singleton('flash', FlashMessageSender::class);
*/
class FlashMessageSender
{
const OLD_FLASH_LARAVEL_SESSION_ENGINE_KEY = '_flash.old';
protected $keyInStorage = '_flash_messages';
/**
* @var \Illuminate\Session\Store
*/
protected $session;
/**
* @var \Illuminate\Support\Collection
*/
protected $messages;
/**
* @param \Illuminate\Session\Store $session
*/
public function __construct(Store $session)
{
$this->session = $session;
$this->messages = new Collection();
$this->ageFlash();
}
/**
* Set specific key for session storage.
*
* @param string $key
*/
public function setStorageKey($key)
{
$this->keyInStorage = $key;
}
/**
* Flash an information message.
*
* @param string $message
* @param array $data
* @return object
*/
public function info($message, array $data = [])
{
return $this->addMessage($message, 'info', $data);
}
/**
* Flash a success message.
*
* @param string $message
* @param array $data
* @return object
*/
public function success($message, array $data = [])
{
return $this->addMessage($message, 'success', $data);
}
/**
* Flash an error message.
*
* @param string $message
* @param array $data
* @return object
*/
public function error($message, array $data = [])
{
return $this->addMessage($message, 'danger', $data);
}
/**
* Flash a warning message.
*
* @param string $message
* @param array $data
* @return object
*/
public function warning($message, array $data = [])
{
return $this->addMessage($message, 'warning', $data);
}
/**
* Flash a general message.
*
* @param string $message
* @param string $level
* @param array $data
* @return object
*/
public function addMessage($message, $level = 'info', array $data = [])
{
$msg_object = (object) array_merge($data, ['text' => $message, 'level' => $level]);
$this->messages->prepend($msg_object);
$this->flash();
return $msg_object;
}
/**
* Return collection messages by level or all.
*
* @param string|null $level
* @return \Illuminate\Support\Collection
*/
public function getMessages($level = null)
{
$this->flushFlash();
$messages = array_merge(
$this->session->get($this->keyInStorage, []),
$this->session->get($this->keyInStorage . '_old', [])
);
$messages = (new Collection($messages))->map(function ($message) {
return (object) $message;
});
if (null === $level) {
return $messages;
}
return $messages->filter(function ($message) use ($level) {
return $message->level === $level;
});
}
/**
* Alias for getMessages method.
*
* @param string|null $level
* @return \Illuminate\Support\Collection
*/
public function messages($level = null)
{
return $this->getMessages($level);
}
/**
* Store current messages to flash session store.
*/
protected function flash()
{
$data = $this->messages
->map(function ($message) {
return (array) $message;
})
->toArray();
$this->session->flash($this->keyInStorage, $data);
}
/**
* Remove old messages to special message list.
*/
protected function ageFlash()
{
if (! $this->session->has($this->keyInStorage)) {
return;
}
$old_messages = $this->session->pull($this->keyInStorage);
$key_old = $this->keyInStorage . '_old';
$this->session->put($key_old, $old_messages);
$this->session->push(self::OLD_FLASH_LARAVEL_SESSION_ENGINE_KEY, $key_old);
}
/**
* Mark notices as old.
*/
protected function flushFlash()
{
$this->session->push(self::OLD_FLASH_LARAVEL_SESSION_ENGINE_KEY, $this->keyInStorage);
}
}
<?php
//app/Servides/Foundation/helpers.php
if (! function_exists('flash')) {
/**
* Make a flash message or retrieve a FlashMessageSender instance.
*
* @param string $message
* @param array $data
* @return \Adteam\Services\Foundation\FlashMessageSender
*/
function flash(string $message = null, array $data = [])
{
if (is_null($message)) {
return app('flash');
}
return app('flash')->info($message, $data);
}
}
@Ellrion
Copy link
Author

Ellrion commented Mar 5, 2018

@andrey-helldar, Возможно что то сменилось с альясами в новых версиях лары.
В комментарии я поправлю конечно на всякий случай.
Тебе возможно будет интересен соответствующий пакет: https://github.com/Larapac/FlashMessages

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment