【问题标题】:Displaying data on view blade from database Laravel Notifications从数据库 Laravel Notifications 在视图刀片上显示数据
【发布时间】:2020-07-26 04:31:46
【问题描述】:

我是使用 laravel 的新手。当我尝试使用 laravel 通知在网站上显示数据时,我遇到了一个问题。 这是我的代码:

GameBiddedNotification.php:

public function toDatabase($notifiable)
{
    return[
        'title' => $this->details['title'],
        'text' => $this->details['text']
    ];
}

这是数据库模板,在数据列中:

{"title":"hg","text":"\u10db\u10dd\u10d7\u10d0\u10db\u10d0\u10e8\u10d4 \u10e8\u10d4\u10db\u10dd\u10d5\u10d8\u10d3\u10d0"}

这是我的刀片:

                  @foreach(auth()->user()->unreadNotifications as $notification)
              @php
              $data = json_decode($notification,true);
              $test = $data['title'] ['text'];
              @endphp

              <a class="dropdown-item preview-item">
                <div class="preview-thumbnail">
                  <div class="preview-icon bg-dark rounded-circle">
                    <i class="mdi mdi-xbox-controller text-success"></i>
                  </div>
                </div>
                <div class="preview-item-content">
                  {{-- <p class="preview-subject mb-1">{{ $notification->data['title'] }}</p> --}}
                  <p class="text-muted ellipsis mb-0">{{ $test }}</p>
                </div>
              </a>
              @endforeach

我尝试了多种方法,例如:

{{ $notification->data['title'] }}

,但结果是一样的。我总是收到一个错误提示

ErrorException (E_ERROR)
Undefined index: title

【问题讨论】:

    标签: php laravel laravel-blade


    【解决方案1】:

    根据您的问题,标题和文本存储在“数据”列中,

       @foreach(auth()->user()->unreadNotifications as $notification) 
            <a class="dropdown-item preview-item">
                <div class="preview-thumbnail">
                    <div class="preview-icon bg-dark rounded-circle">
                        <i class="mdi mdi-xbox-controller text-success"></i>
                    </div>
                </div>
                <div class="preview-item-content">
                    <p class="preview-subject mb-1">{{ $notification->data['title'] }}</p>
                    <p class="text-muted ellipsis mb-0">{{ $notification->data['text'] }}</p>
                </div>
            </a>
        @endforeach
    

    【讨论】:

    • 它会抛出一个错误:“json_decode() 期望参数 1 是字符串,给定数组”
    • 编辑了答案。请检查一次。
    • 嗯,“未定义的索引:文本”。
    【解决方案2】:

    如果在 Notification-model 上正确设置$casts 将数据列转换为数组,则无需在刀片上使用 json_decode。

    $casts = [ 'data' =&gt; 'array' ];

    你的模型是什么样子的?

    顺便说一句:您通常应该避免使用@php——它通常会指出属于控制器的代码。我想这是仅测试代码?相反,最好dd($notification); 来检查数据属性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-09
      • 1970-01-01
      • 2023-01-08
      • 2020-05-08
      • 2016-11-20
      • 2022-01-11
      • 2020-08-19
      • 2021-10-17
      相关资源
      最近更新 更多