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

How to get data out of the notifications?[Error retrieving data] laravel 5.8

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

Undefined index: thread (View: C:\Users\Merlijn\AppData\Roaming\Composer\Laravel Projects\Forum\resources\views\layouts\partials\notification\replied_to_thread.blade.php) (View: C:\Users\Merlijn\AppData\Roaming\Composer\Laravel Projects\Forum\resources\views\layouts\partials\notification\replied_to_thread.blade.php) (View: C:\Users\Merlijn\AppData\Roaming\Composer\Laravel Projects\Forum\resources\views\layouts\partials\notification\replied_to_thread.blade.php) (View: 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 而是说它未定义

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']