在我的laravel应用程序中,我将JSON文件转换成一个laravel集合,然后执行。我将该方法作为一个laravel命令执行,我回显变量,以便确定它没有丢失任何内容。
我收到错误:
Illuminate\Support\ItemNotFoundException
我的拉拉威尔方法:
$json = File::get(base_path().'/json/Notifications.json');
$notifications = json_decode($json, true);
$notifications = collect($notifications);
echo count($notifications);
echo $this->time;
$dayOfTheWeek = Carbon::now()->dayOfWeek;
$todayNotification = $notifications->where('day','=',$dayOfTheWeek)->firstOrFail();
我的通知. json文件
[
{ "day":1, "time":1,"title":"woo", "body":"notifBody1", "image" : "default"},
{ "day":1, "time":2,"title":"woo", "body":"notifBody2", "image" : "default"},
{ "day":1, "time":3,"title":"woo", "body":"notifBody3", "image" : "default"},
{ "day":2, "time":1,"title":"woo", "body":"notifBody4", "image" : "default"},
{ "day":2, "time":2,"title":"woo", "body":"notifBody5", "image" : "default"},
{ "day":2, "time":3,"title":"woo", "body":"notifBody6", "image" : "default"},
{ "day":3, "time":1,"title":"woo", "body":"notifBody7", "image" : "default"},
{ "day":3, "time":2,"title":"woo", "body":"notifBody8", "image" : "default"},
{ "day":3, "time":3,"title":"woo", "body":"notifBody9", "image" : "default"},
{ "day":4, "time":1,"title":"woo", "body":"notifBody10", "image" : "default"},
{ "day":4, "time":2,"title":"woo", "body":"notifBody11", "image" : "default"},
{ "day":4, "time":3,"title":"woo", "body":"notifBody12", "image" : "default"},
{ "day":5, "time":1,"title":"woo", "body":"notifBody13", "image" : "default"},
{ "day":5, "time":2,"title":"woo", "body":"notifBody14", "image" : "default"},
{ "day":5, "time":3,"title":"woo", "body":"notifBody15", "image" : "default"},
{ "day":6, "time":1,"title":"woo", "body":"notifBody16", "image" : "default"},
{ "day":6, "time":2,"title":"woo", "body":"notifBody17", "image" : "default"},
{ "day":6, "time":3,"title":"woo", "body":"notifBody17", "image" : "default"},
{ "day":7, "time":1,"title":"woo", "body":"notifBody18", "image" : "default"},
{ "day":7, "time":2,"title":"woo", "body":"notifBody19", "image" : "default"},
{ "day":7, "time":3,"title":"woo", "body":"notifBody20", "image" : "default"}
]
2条答案
按热度按时间hmae6n7t1#
dayOfWeek
是0到6。所以它不会匹配你的JSON
数据。相反,你可以使用dayOfWeekIso
,它是索引到你的喜好。所以改变这一行,我认为它应该工作的预期。afdcj2ne2#
当找不到满足where条件的项时,对
$notifications
集合调用的firstOrFail方法将引发错误Illuminate\Support\ItemNotFoundException
。您可以捕获此异常并进行适当的处理,例如:
或者,您可以使用第一个方法代替
firstOrFail
,如果没有找到项,firstOrFail
将返回null:然后,您可以检查
$todayNotification
是否为空,以处理未找到项的情况。