"Undefined offset: 1"拉拉维尔的错误。这是怎么回事?



我正在尝试在我的视图中传递我在数据库中的所有帖子,但弹出了此错误。

以下是我的观点:

<ul>
{{ <li>@foreach ($posts => $posts) }}
<div class="row section scrollspy" style="padding:10px; margin-top:10px;">
<div class="content-box col s12" style="padding:20px; margin-top:40px; background: #f2f2f2; border-radius:10px;">
<div class="i_title" style="text-align:center; margin: -57px 0 0 0;">
<a href="/profile" class="tooltip"><img class="responsive-img circle" src="images/profile_picture.jpg" style="width:60px; box-shadow: 0 6px 10px 0 rgba(0, 0, 0, 0.2);"><span class="tooltiptext">@Username{{ $user->username }}</span></a>
</div>
<p class="col s12"{{ $post->post }}</p>
</div>
</div>
{{ @endforeach</li> }}
</ul>

我的控制器:

<?php
namespace AppHttpControllers;
use IlluminateHttpRequest;
use IlluminateSupportFacadesDB;
class UserController extends Controller
{
public function getUsers()
{
$user = DB::table('users')->get();
return view('layouts/welcomeView', ['users' => $user]);
}
public function getPosts()
{
$posts = DB::table('posts')->get();
return view('layouts/welcomeView', ['posts' => $posts]);
}
}

我的数据库有一些帖子,所以这不是问题。我认为问题在于我没有很好地传递帖子的变量。我能做什么??

这有几个问题。

首先,你混合了刀片指令。{{ }}用于回显某些内容。{{}}里面的任何内容都被解释为 PHP,并被传递到函数中以执行一些转义并被回显出来。因此,当您执行{{ <li>@foreach ($posts => $posts) }}时,Blade编译器会尝试<li>@foreach ($posts => $posts)视为PHP代码,这将导致语法错误。@foreach不属于{{ }}

其次,我注意到你的@foreach里面有$posts => $posts.注意到箭头两侧的变量是否相同吗?这无疑是一个错别字,但它会导致循环的第一次迭代用第一个条目覆盖$posts变量,循环将尝试继续迭代这个新的单个值。这可能会导致您看到的错误。

这可能更接近您要查找的内容:

<ul>
@foreach ($posts => $post)
<li>
<div class="row section scrollspy" style="padding:10px; margin-top:10px;">
<div class="content-box col s12" style="padding:20px; margin-top:40px; background: #f2f2f2; border-radius:10px;">
<div class="i_title" style="text-align:center; margin: -57px 0 0 0;">
<a href="/profile" class="tooltip"><img class="responsive-img circle" src="images/profile_picture.jpg" style="width:60px; box-shadow: 0 6px 10px 0 rgba(0, 0, 0, 0.2);"><span class="tooltiptext">@Username{{ $user->username }}</span></a>
</div>
<p class="col s12"{{ $post->post }}</p>
</div>
</div>
</li>
@endforeach
</ul>

将视图更改为;

<ul>
<li> 
@foreach ($posts => $post)
<div class="row section scrollspy" style="padding:10px; margin-top:10px;">
<div class="content-box col s12" style="padding:20px; margin-top:40px; background: #f2f2f2; border-radius:10px;">
<div class="i_title" style="text-align:center; margin: -57px 0 0 0;">
<a href="/profile" class="tooltip"><img class="responsive-img circle" src="images/profile_picture.jpg" style="width:60px; box-shadow: 0 6px 10px 0 rgba(0, 0, 0, 0.2);"><span class="tooltiptext">@Username{{ $user->username }}</span></a>
</div>
<p class="col s12"{{ $post->post }}</p>
</div>
</div>
@endforeach
</li>
</ul>

如果未在某处定义,则可能需要移动@Username

通常,在获取数组之前检查数组中是否有某些内容是一种很好的做法。

您可以通过实践来实现这一目标;

@if(! $posts->isEmpty()) 
@foreach ($posts => $post)
....
@endforeach
@endif

相关内容