在 Laravel 中,在 session 中传递不同类型的 flash 消息的最佳方式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21004310/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 02:42:29  来源:igfitidea点击:

In Laravel, the best way to pass different types of flash messages in the session

sessionlaravellaravel-4

提问by harryg

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 either by going

我正在 Laravel 中制作我的第一个应用程序,并试图了解会话 Flash 消息。据我所知,在我的控制器操作中,我可以通过

Redirect::to('users/login')->with('message', 'Thanks for registering!'); //is this actually OK?

For the case of redirecting to another route, or

对于重定向到另一条路由的情况,或

Session::flash('message', 'This is a message!'); 

In my master blade template I'd then have:

在我的主刀片模板中,我将拥有:

@if(Session::has('message'))
<p class="alert alert-info">{{ Session::get('message') }}</p>
@endif

As you may have noticed I'm using Bootstrap 3 in my app and would like to make use of the different message classes: alert-info, alert-warning, alert-dangeretc.

:正如你可能我在我的应用程序中使用自举3,并想使不同的消息类别的使用已经注意到alert-infoalert-warningalert-danger等。

Assuming that in my controller I know what type of message I'm setting, what's the best way to pass and display it in the view? Should I set a separate message in the session for each type (e.g. Session::flash('message_danger', 'This is a nasty message! Something's wrong.');)? Then I'd need a separate if statement for each message in my blade template.

假设在我的控制器中我知道我正在设置什么类型的消息,那么在视图中传递和显示它的最佳方法是什么?我应该在会话中为每种类型(例如Session::flash('message_danger', 'This is a nasty message! Something's wrong.');)设置单独的消息吗?然后我需要为我的刀片模板中的每条消息使用一个单独的 if 语句。

Any advice appreciated.

任何建议表示赞赏。

回答by msturdy

One solution would be to flash two variables into the session:

一种解决方案是将两个变量闪存到会话中:

  1. The message itself
  2. The "class" of your alert
  1. 消息本身
  2. 警报的“类”

for example:

例如:

Session::flash('message', 'This is a message!'); 
Session::flash('alert-class', 'alert-danger'); 

Then in your view:

那么在你看来:

@if(Session::has('message'))
<p class="alert {{ Session::get('alert-class', 'alert-info') }}">{{ Session::get('message') }}</p>
@endif

Note I've put a default valueinto the Session::get(). that way you only need to override it if the warning should be something other than the alert-infoclass.

请注意,我已将默认值放入Session::get(). 这样你只需要在警告不是alert-info类的时候覆盖它。

(that is a quick example, and untested :) )

(这是一个简单的例子,未经测试:))

回答by danelips

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');

回答by Antonio Carlos Ribeiro

My way is to always Redirect::back() or Redirect::to():

我的方法是始终 Redirect::back() 或 Redirect::to():

Redirect::back()->with('message', 'error|There was an error...');

Redirect::back()->with('message', 'message|Record updated.');

Redirect::to('/')->with('message', 'success|Record updated.');

I have a helper function to make it work for me, usually this is in a separate service:

我有一个辅助函数可以让它对我来说有效,通常这是在一个单独的服务中:

function displayAlert()
{
      if (Session::has('message'))
      {
         list($type, $message) = explode('|', Session::get('message'));

         $type = $type == 'error' : 'danger';
         $type = $type == 'message' : 'info';

         return sprintf('<div class="alert alert-%s">%s</div>', $type, message);
      }

      return '';
}

And in my view or layout I just do

在我的观点或布局中,我只是这样做

{{ displayAlert() }}

回答by clemquinones

You can make a multiple messages and with different types. Follow these steps below:

您可以制作多条消息并使用不同的类型。请按照以下步骤操作:

  1. Create a file: "app/Components/FlashMessages.php"
  1. 创建一个文件:“ 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);
  }
}
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);
  }
}
  1. On your base controller "app/Http/Controllers/Controller.php".
  1. 在您的基本控制器“ 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;
}
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 FlashMessagestrait available to all controllers that extending this class.

这将使FlashMessages所有扩展此类的控制器都可以使用该特征。

  1. Create a blade template for our messages: "views/partials/messages.blade.php"
  1. 为我们的消息创建一个刀片模板:“ 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
@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
  1. On "boot()" method of "app/Providers/AppServiceProvider.php":
  1. 关于“”的boot()“方法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);
      });
    }

    ...
}
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 $messagesvariable available to "views/partials/message.blade.php" template whenever it is called.

这将使$messages变量views/partials/message.blade.php在调用时可用于“ ”模板。

  1. On your template, include our messages template - "views/partials/messages.blade.php"
  1. 在您的模板上,包括我们的消息模板 - " 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>
<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.

您只需要在您希望在页面上显示消息的任何位置包含消息模板。

  1. On your controller, you can simply do this to push flash messages:
  1. 在您的控制器上,您可以简单地执行此操作来推送 Flash 消息:
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.');
  }

  ...
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.

希望能帮到你。

回答by Richelly Italo

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!

是的,它确实有效!

回答by Ayobami Opeyemi

Another solution would be to create a helper class How to Create helper classes here

另一种解决方案是创建一个助手类 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

回答by SupaMonkey

Not a big fan of the solutions provided (ie: multiple variables, helper classes, looping through 'possibly existing variables'). Below is a solution that instead uses an array as opposed to two separate variables. It's also easily extendable to handle multiple errors should you wish but for simplicity, I've kept it to one flash message:

不太喜欢所提供的解决方案(即:多个变量、辅助类、循环遍历“可能存在的变量”)。下面是一个使用数组而不是两个单独变量的解决方案。如果您愿意,它也可以轻松扩展以处理多个错误,但为简单起见,我将其保留为一条 flash 消息:

Redirect with flash message array:

使用 flash 消息数组重定向:

    return redirect('/admin/permissions')->with('flash_message', ['success','Updated Successfully','Permission "'. $permission->name .'" updated successfully!']);

Output based on array content:

基于数组内容的输出:

@if(Session::has('flash_message'))
    <script type="text/javascript">
        jQuery(document).ready(function(){
            bootstrapNotify('{{session('flash_message')[0]}}','{{session('flash_message')[1]}}','{{session('flash_message')[2]}}');
        });
    </script>
@endif

Unrelated since you might have your own notification method/plugin - but just for clarity - bootstrapNotify is just to initiate bootstrap-notify from http://bootstrap-notify.remabledesigns.com/:

不相关,因为您可能有自己的通知方法/插件 - 但只是为了清楚起见 - bootstrapNotify 只是从http://bootstrap-notify.remabledesigns.com/启动 bootstrap-notify :

function bootstrapNotify(type,title = 'Notification',message) {
    switch (type) {
        case 'success':
            icon = "la-check-circle";
            break;
        case 'danger':
            icon = "la-times-circle";
            break;
        case 'warning':
            icon = "la-exclamation-circle";
    }

    $.notify({message: message, title : title, icon : "icon la "+ icon}, {type: type,allow_dismiss: true,newest_on_top: false,mouse_over: true,showProgressbar: false,spacing: 10,timer: 4000,placement: {from: "top",align: "right"},offset: {x: 30,y: 30},delay: 1000,z_index: 10000,animate: {enter: "animated bounce",exit: "animated fadeOut"}});
}

回答by ivahidmontazer

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:

消息布局,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'),
])

回答by Ikong

I usually do this

我通常这样做

in my store() function i put success alert once it saved properly.

在我的 store() 函数中,一旦正确保存,我就会发出成功警报。

\Session::flash('flash_message','Office successfully updated.');

in my destroy() function, I wanted to color the alert red so to notify that its deleted

在我的 destroy() 函数中,我想将警报着色为红色,以便通知它已删除

\Session::flash('flash_message_delete','Office successfully deleted.');

Notice, we create two alerts with different flash names.

请注意,我们创建了两个具有不同闪存名称的警报。

And in my view, I will add condtion to when the right time the specific alert will be called

在我看来,我会在适当的时间调用特定警报时添加条件

@if(Session::has('flash_message'))
    <div class="alert alert-success"><span class="glyphicon glyphicon-ok"></span><em> {!! session('flash_message') !!}</em></div>
@endif
@if(Session::has('flash_message_delete'))
    <div class="alert alert-danger"><span class="glyphicon glyphicon-ok"></span><em> {!! session('flash_message_delete') !!}</em></div>
@endif

Here you can find different flash message stlyes Flash Messages in Laravel 5

在这里你可以找到Laravel 5 中不同的 flash message stlyes Flash Messages

回答by Emeka Mbah

You could use Laravel Macros.

您可以使用 Laravel 宏。

You can create macros.phpin app/helpersand include it routes.php.

您可以macros.phpapp/helpersroutes.php 中创建并包含它。

if you wish to put your macros in a class file instead, you can look at this tutorial: http://chrishayes.ca/blog/code/laravel-4-object-oriented-form-html-macros-classes-service-provider

如果你想把你的宏放在一个类文件中,你可以看看这个教程:http: //chrishayes.ca/blog/code/laravel-4-object-oriented-form-html-macros-classes-service-提供者

HTML::macro('alert', function($class='alert-danger', $value="",$show=false)
{

    $display = $show ? 'display:block' : 'display:none';

    return
        '<div class="alert '.$class.'" style="'.$display.'">
            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
            <strong><i class="fa fa-times"></i></strong>'.$value.'
        </div>';
});

In your controller:

在您的控制器中:

Session::flash('message', 'This is so dangerous!'); 
Session::flash('alert', 'alert-danger');

In your View

在你看来

@if(Session::has('message') && Session::has('alert') )
  {{HTML::alert($class=Session::get('alert'), $value=Session::get('message'), $show=true)}}
@endif