Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Session 在Laravel中,在会话中传递不同类型的flash消息的最佳方式_Session_Laravel_Laravel 4 - Fatal编程技术网

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

Session 在Laravel中,在会话中传递不同类型的flash消息的最佳方式,session,laravel,laravel-4,Session,Laravel,Laravel 4,我在Laravel制作了我的第一个应用程序,并试图让我的头脑了解会话flash消息。据我所知,在控制器操作中,我可以通过 Redirect::to('users/login')->with('message', 'Thanks for registering!'); //is this actually OK? 对于重定向到其他路由的情况,或 Session::flash('message', 'This is a message!'); 在我的主刀片模板中,我有: @if(Sess

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

Redirect::to('users/login')->with('message', 'Thanks for registering!'); //is this actually OK?
对于重定向到其他路由的情况,或

Session::flash('message', 'This is a message!'); 
在我的主刀片模板中,我有:

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

{{Session::get('message')}

@恩迪夫
正如您可能已经注意到的,我在我的应用程序中使用Bootstrap 3,并希望使用不同的消息类:
警报信息
警报警告
警报危险

假设在我的控制器中,我知道要设置的消息类型,那么在视图中传递和显示消息的最佳方式是什么?我是否应该在会话中为每种类型设置单独的消息(例如,
session::flash(“message\u danger”,“这是一条令人讨厌的消息!有问题”);
?然后,我需要为刀片模板中的每条消息使用单独的if语句


非常感谢您的建议。

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

  • 信息本身
  • 警报的“类”
  • 例如:

    Session::flash('message', 'This is a message!'); 
    Session::flash('alert-class', 'alert-danger'); 
    
    那么在你看来,

    @if(Session::has('message'))
    <p class="alert {{ Session::get('alert-class', 'alert-info') }}">{{ Session::get('message') }}</p>
    @endif
    
    <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>
    
    @if(会话::has('message'))
    

    {{Session::get('message')}

    @恩迪夫
    注意,我在
    会话::get()
    中添加了一个。这样,只有当警告不是
    警报信息
    类时,才需要覆盖它


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

    另一个解决方案是创建一个helper类

    在你看来

    @if(Session::has('message'))
        {{Session::get('message')}}
    @endif
    

    我的方法是始终重定向::back()或重定向::to():

    我有一个助手功能,可以让它为我工作,通常这是在一个单独的服务中:

    use Illuminate\Support\Facades\Session;
    
    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 '';
    }
    
    在你看来:

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

    您可以使用Laravel宏

    您可以在
    app/helpers
    中创建
    macros.php
    ,并将其包含在routes.php中

    如果希望将宏放在类文件中,可以查看本教程:

    在你看来

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

    只需返回您希望处理的“标志”,而无需使用任何其他用户函数。 控制员:

    Session::flash('alert-danger', 'danger');
    Session::flash('alert-warning', 'warning');
    Session::flash('alert-success', 'success');
    Session::flash('alert-info', 'info');
    
    Session::flash('message', 'This is so dangerous!'); 
    Session::flash('alert', 'alert-danger');
    
    return \Redirect::back()->withSuccess( 'Message you want show in View' );
    
    Redirect::to('/path')->with('message', 'your message'); 
    
    请注意,我使用了“成功”标志

    观点:

    @if( Session::has( 'success' ))
         {{ Session::get( 'success' ) }}
    @elseif( Session::has( 'warning' ))
         {{ Session::get( 'warning' ) }} <!-- here to 'withWarning()' -->
    @endif
    
    @if(会话::has('success'))
    {{Session::get('success')}
    @elseif(会话::has('warning'))
    {{Session::get('warning')}
    @恩迪夫
    

    是的,它真的有效

    对于我的应用程序,我制作了一个助手函数:

    function message( $message , $status = 'success', $redirectPath = null )
    {
         $redirectPath = $redirectPath == null ? back() : redirect( $redirectPath );
    
         return $redirectPath->with([
             'message'   =>  $message,
             'status'    =>  $status,
        ]);
    }
    
    消息布局,
    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
    
    我通常这样做

    在my store()函数中,一旦成功保存,我会将成功警报放入其中

    \Session::flash('flash_message','Office successfully updated.');
    
    在destroy()函数中,我想将警报涂成红色,以便通知它已被删除

    \Session::flash('flash_message_delete','Office successfully deleted.');
    
    请注意,我们创建了两个具有不同闪存名称的警报

    在我看来,我将在调用特定警报的正确时间添加条件

    @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
    
    @if(会话::has('flash_message'))
    {!!会话('flash_message')
    @恩迪夫
    @如果(会话::has('flash_message_delete'))
    {!!会话('flash\u message\u delete')
    @恩迪夫
    

    在这里,您可以找到不同的flash消息stlyes

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

  • 创建一个文件:“
    app/Components/FlashMessages.php
  • 在基本控制器上“
    app/Http/Controllers/controller.php
  • 这将使扩展该类的所有控制器都可以使用
    FlashMessages
    trait

  • 为我们的消息创建一个刀片模板:“
    视图/partials/messages.blade.php
  • 这将使“
    视图/partials/message.blade.php
    ”模板无论何时调用都可以使用
    $messages
    变量

  • 在您的模板上,包括我们的消息模板-“
    views/partials/messages.blade.php

  • 希望它能对您有所帮助。

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

    使用闪存消息阵列重定向:

        return redirect('/admin/permissions')->with('flash_message', ['success','Updated Successfully','Permission "'. $permission->name .'" updated successfully!']);
    
    基于数组内容的输出:

    @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
    

    我认为下面的代码行越少越好

            session()->flash('toast', [
            'status' => 'success', 
            'body' => 'Body',
            'topic' => 'Success']
        );
    
    我用的是烤面包机包,但你可以在你的视图中看到这样的东西

                 toastr.{{session('toast.status')}}(
                  '{{session('toast.body')}}', 
                  '{{session('toast.topic')}}'
                 );
    
    在控制器中:

    Session::flash('alert-danger', 'danger');
    Session::flash('alert-warning', 'warning');
    Session::flash('alert-success', 'success');
    Session::flash('alert-info', 'info');
    
    Session::flash('message', 'This is so dangerous!'); 
    Session::flash('alert', 'alert-danger');
    
    return \Redirect::back()->withSuccess( 'Message you want show in View' );
    
    Redirect::to('/path')->with('message', 'your message'); 
    

    在刀片中按所需模式显示刀片中的消息:

    @if(Session::has('message'))
        <div class="alert alert-className">
            {{session('message')}}
        </div>
    @endif
    
    @if(会话::has('message'))
    {{session('message')}
    @恩迪夫
    
    只需在会话中发送数组而不是字符串,如下所示:

    Session::flash('message', ['text'=>'this is a danger message','type'=>'danger']);
    
    @if(Session::has('message'))
        <div class="alert alert-{{session('message')['type']}}">
            {{session('message')['text']}}
        </div>
    @endif
    
    Session::flash('message',['text'=>'这是一条危险消息','type'=>'danger']);
    @if(会话::has('message'))
    {{会话('message')['text']}
    @恩迪夫
    
    我发现了一种优雅的闪现信息的方式。它是由来自拉腊卡斯特的杰弗里·韦制作的。 过来看。。。

    如果要使用引导警报使视图更具交互性。您可以这样做:

    Session::flash('message', ['text'=>'this is a danger message','type'=>'danger']);
    
    @if(Session::has('message'))
        <div class="alert alert-{{session('message')['type']}}">
            {{session('message')['text']}}
        </div>
    @endif
    
    在你的职能中:-

    if($author->save()){
        Session::flash('message', 'Author has been successfully added');
        Session::flash('class', 'success'); //you can replace success by [info,warning,danger]
        return redirect('main/successlogin');
    
    在你看来:-

    @if(Session::has('message'))
        <div class="alert alert-{{Session::get('class')}} alert-dismissible fade show w-50 ml-auto alert-custom"
            role="alert">
            {{ Session::get('message') }}
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
    @endif
    
    @if(会话::has('message'))
    {{Session::get('message')}
    &时代;
    @恩迪夫
    
    有趣的是,我不知道
    Session::get()
    的默认参数会非常方便。与大多数flash消息解决方案一样,它只处理一条消息。因此,经常需要能够发出一堆消息,每个消息可能具有不同的严重性,并将它们全部显示出来。。。为什么每个人都对此投赞成票?@Goowik-说这会适得其反,而不提供更有效的解决方案是适得其反的
            session()->flash('toast', [
            'status' => 'success', 
            'body' => 'Body',
            'topic' => 'Success']
        );
    
                 toastr.{{session('toast.status')}}(
                  '{{session('toast.body')}}', 
                  '{{session('toast.topic')}}'
                 );
    
    Redirect::to('/path')->with('message', 'your message'); 
    
    Session::flash('message', 'your message'); 
    
    @if(Session::has('message'))
        <div class="alert alert-className">
            {{session('message')}}
        </div>
    @endif
    
    Session::flash('message', ['text'=>'this is a danger message','type'=>'danger']);
    
    @if(Session::has('message'))
        <div class="alert alert-{{session('message')['type']}}">
            {{session('message')['text']}}
        </div>
    @endif
    
    if($author->save()){
        Session::flash('message', 'Author has been successfully added');
        Session::flash('class', 'success'); //you can replace success by [info,warning,danger]
        return redirect('main/successlogin');
    
    @if(Session::has('message'))
        <div class="alert alert-{{Session::get('class')}} alert-dismissible fade show w-50 ml-auto alert-custom"
            role="alert">
            {{ Session::get('message') }}
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
    @endif