1

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

未定义索引:线程(查看:C:\Users\Merlijn\AppData\Roaming\Composer\Laravel Projects\Forum\resources\views\layouts\partials\notification\replied_to_thread.blade.php)(查看:C:\Users\Merlijn \AppData\Roaming\Composer\Laravel Projects\Forum\resources\views\layouts\partials\notification\replied_to_thread.blade.php)(查看:C:\Users\Merlijn\AppData\Roaming\Composer\Laravel Projects\Forum\resources \views\layouts\partials\notification\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 却说它未定义

4

1 回答 1

4

data是一个包含 json 格式的字符串。如果你不告诉 PHP 这个信息,PHP 只会把它解释为一个没有键的字符串。

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

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

更新:我假设您使用 Eloquent 获得这些值?如果是这样,您可以让 eloquent 为您解析这些 json 字符串

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

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

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

于 2019-03-19T14:01:36.357 回答