英文:
whenever I run a loop it seems to turn my object null after
问题
我以前从未遇到过这种情况。在 Laravel 8 中,每当我遍历一个集合时,它之后就变成了null。
示例:
$loops = Loops::get();
在循环内部,我有以下代码:
public function loopNotifications()
{
return $this->hasMany(LoopNotifications::class, 'loop_id', 'id');
}
@if($loop->loopNotifications->count())
@foreach($loop->loopNotifications as $loopNotification)
<li class="px-6 py-2 border-b border-gray-200 w-full">
<div class="text-lg font-medium">{!!$loopNotification->convertToReadable()!!}</div>
</li>
@endforeach
@endif
在运行这段代码之前,我会使用dd()
函数输出循环的内容,而一切都正常。
但在运行相同的dd()
函数之后,循环变成了null。这对我运行的每个foreach循环都发生了。我开始编写for循环,只是为了绕过这个问题,但现在编写所有这些额外的代码变得很令人沮丧。
有人遇到过这个问题吗?
英文:
I have never encountered this before. In Laravel 8, every time I iterate through a collection, it becomes null after.
Example:
$loops = Loops::get();
inside of loops I have
public function loopNotifications()
{
return $this->hasMany(LoopNotifications::class, 'loop_id', 'id');
}
@if($loop->loopNotifications->count())
@foreach($loop->loopNotifications as $loopNotification)
<li class="px-6 py-2 border-b border-gray-200 w-full">
<div class="text-lg font-medium">{!!$loopNotification->convertToReadable()!!}
</div>
</li>
@endforeach
@endif
Before I run this I dd() the loop, and it's all there
After I run the same dd() and it's null. This is happening to every single foreach I run. I started to write for statements just to get past this, but at this point It's frustrating to write all the extra code.
Has anyone had this issue.
答案1
得分: 0
不要在Blade中使用$loop
作为变量名。Laravel使用这个变量名来提供关于循环本身的信息,正如您猜得正确的那样。请尝试更改变量名。
另外,你可以考虑使用??
操作符来代替将整个内容放在@if
块中(假设你已经将$loop
改为$l
):
@foreach($l->loopNotifications??[] as $loopNotification)
<li class="px-6 py-2 border-b border-gray-200 w-full">
<div class="text-lg font-medium">{!! $loopNotification->convertToReadable() !!} </div>
</li>
@endforeach
这将在$loop->loopNotifications
为空时返回一个空数组。这不是必需的,你的方法也可以正常工作,但在我看来,这样更清晰。
英文:
Don't use $loop
as a variable in blade.
Laravel uses this variable name to give you insights about the loop itself as you were guessing correctly.
Renaming the variable and try again.
Also on a sidenote you could use the ??
operator instead of putting the whole inside a @if block: (considering you named $loop
to $l
)
@foreach($l->loopNotifications??[] as $loopNotification)
<li class="px-6 py-2 border-b border-gray-200 w-full">
<div class="text-lg font-medium">{!!$loopNotification->convertToReadable()!!}
</div>
</li>
@endforeach
This fallsback to an empty array if $loop->loopNotifications is null. It's not required, yours works as well, but IMHO it's cleaner.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论