如何从通知中获取数据?[错误检索数据] laravel 5.8

时间:2019-03-19 13:56:45

标签: laravel laravel-notification laravel-5.8

当用户在某个线程上发帖时,它会发送通知,然后在导航栏上显示一个下拉菜单,用户可以在其中看到他的所有通知,但是当我尝试打开它时,会出现错误

  

未定义索引:线程(视图:   C:\ Users \ Merlijn \ AppData \ Roaming \ Composer \ Laravel   项目\论坛\资源\视图\布局\部分\通知\ replied_to_thread.blade.php)   (查看:C:\ Users \ Merlijn \ AppData \ Roaming \ Composer \ Laravel   项目\论坛\资源\视图\布局\部分\通知\ replied_to_thread.blade.php)   (查看:C:\ Users \ Merlijn \ AppData \ Roaming \ Composer \ Laravel   项目\论坛\资源\视图\布局\部分\通知\ replied_to_thread.blade.php)   (查看:C:\ Users \ Merlijn \ AppData \ Roaming \ Composer \ Laravel   Projects \ Forum \ resources \ views \ layouts \ partials \ notification \ replied_to_thread.blade.php)

如果我做dd($notification),我会得到此数据

#attributes: array:8 [▼
"id" => "c055bf7e-8aa0-41d6-b188-d73073dbfefb"
"type" => "App\Notifications\RepliedToThread"
"notifiable_type" => "App\User"
"notifiable_id" => 1
"data" => "{"thread":{"id":2,"subject":"22JSUpdated Updated Updated","thread":"eaweaewarea kejwabnejk.wabe;beh;lkwabhel.kwajewaeaweawe","type":"Question Updated","created_ ▶"
"read_at" => null
"created_at" => "2019-03-19 13:28:11"
"updated_at" => "2019-03-19 13:28:11"
]
#original: array:8 [▼
"id" => "c055bf7e-8aa0-41d6-b188-d73073dbfefb"
"type" => "App\Notifications\RepliedToThread"
"notifiable_type" => "App\User"
"notifiable_id" => 1
"data" => "{"thread":{"id":2,"subject":"22JSUpdated Updated Updated","thread":"eaweaewarea kejwabnejk.wabe;beh;lkwabhel.kwajewaeaweawe","type":"Question Updated","created_ ▶"
"read_at" => null
"created_at" => "2019-03-19 13:28:11"
"updated_at" => "2019-03-19 13:28:11"
]

并且在导航栏中,我试图访问这样的通知数据

@foreach(auth()->user()->unreadNotifications as $notification)
<a href="{{route('thread.show',$notification->data['thread']['id'])}}">

    {{$notification->data['user']['name']}} commented on <strong> 
{{$notification->data['thread']['subject']}}</strong>
</a>
@endforeach

但它说['thread']['id']是未定义的,而在dd中我可以在`array:8中看到

"data" => "{"thread":{"id":2,"subject":"22JSUpdated Updated Updated","thread":"eaweaewarea kejwabnejk.wabe;beh;lkwabhel.kwajewaeaweawe","type":"Question Updated","created_at":"2019-03-19 10:56:58","updated_at":"2019-03-19 10:56:58","user_id":1,"solution":null},"user":{"id":1,"name":"johndoe","email":"johndoe@example.com","email_verified_at":null,"created_at":"2019-03-14 15:34:15","updated_at":"2019-03-14 15:34:15"}} 

但是为什么我找不到那个未定义的线程ID呢?

1 个答案:

答案 0 :(得分:3)

data是包含json格式的字符串。如果您不告诉PHP这些信息,PHP只会将其解释为没有键的字符串。

因此,在使用键之前,您必须解析json:

$data = json_decode($notification->data);
echo $data->thread->id;

更新:我想您是通过Eloquent获得这些值的?如果是这样,您可以let eloquent parse these json strings for you

只需在模型上定义一个$casts属性,然后添加该属性。

protected $casts = [
    'data' => 'array',
];

现在您可以直接使用该属性:$notification->data['thread']['id']