代码之家  ›  专栏  ›  技术社区  ›  Zeth

Laravel中的通知,存储在会话中(如何创建和清除它们)

  •  0
  • Zeth  · 技术社区  · 6 年前

    我正在制作一个应用程序,其中我已将其添加到我的视图模板中,以显示所有通知/状态消息/警报:

    @if ( ! empty( session('notifications') ) )
      @foreach( session('notifications') as $notification )
        <div class="alert alert-{{ $notification['notification_type'] }}" role="alert">
          <strong>{{ $notification['notification_title'] }}</strong> - {{ $notification['notification_message'] }}
        </div>
      @endforeach
    @endif
    

    session('notifications') ,在我的控制器中的任何位置。

    • 每次加载页面时清除所有通知(使用 Session::forget('notifications') 我想, ref
    • 在会话中实例化一个空集合,因此我不需要检查是否为空,如果为空,则添加通知;如果为空,则创建一个空集合,然后添加通知。

    init 在functions.php中。但拉雷维尔的等价物在哪里?

    这是控制Laravel中通知的正确方法吗?我称之为通知,因为没有更好的词。可能是“警报”或“状态”?因为我能看到一个 notification 是相关的,但还是其他的。

    2 回复  |  直到 6 年前
        1
  •  1
  •   Christophe    6 年前

    我想你正在寻找这个: https://laravel.com/docs/5.7/session#flash-data

    正确的?

        2
  •  0
  •   Zeth    6 年前

    把它放在全球可访问的地方( this post 描述了创建这样一个位置的方法):

    function add_flash_message( array $notification){
      session()->flash( 'any_notifications', true );
      if(
        empty( session( 'notification_collection' ) )
      ){
        // If notification_collection is either not set or not a collection
        $new_collection = new \Illuminate\Support\Collection();
        $new_collection->push([
          'notification_title' => $notification['title'],
          'notification_message' => $notification['message'],
          'notification_type' => $notification['type'],
        ]);
        session()->flash( 'notification_collection', $new_collection );
      } else {
        // Add to the notification-collection
        $notification_collection = \Session::get( 'notification_collection' );
        $notification_collection->push( [
          'notification_title' => $notification['title'],
          'notification_message' => $notification['message'],
          'notification_type' => $notification['type'],
        ]);
        session()->flash( 'notification_collection', $notification_collection );
      }
    }
    

    在工作流中

    add_flash_message( [
      'title' => 'The file does not exist',
      'message' => 'The chosen file/path does not seem to exist.',
      'type' => 'danger'
    ] );
    

    在视图/刀片文件中

    @if( !empty( Session( 'any_notifications' ) ) )
      @foreach (Session('notification_collection') as $notification)
        <div class="alert alert-{{ $notification['notification_type'] }}" role="alert">
          <strong>{{ $notification['notification_title'] }}</strong> - {{ $notification['notification_message'] }}
          <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
        </div>
      @endforeach
    @endif