我对Laravel很新。我在使用Controller和新创建的blade.php
时发现了这个令人困惑的错误这是我的控制器
class UsersController extends Controller
{
public function index(){
$users[] = [
'0' => [
'first_name' => 'James',
'last_name' => 'Bond',
'location' => 'UK'
],
'1' => [
'first_name' => 'Jimmy',
'last_name' => 'Carter',
'location' => 'USA'
]
];
return view('admin.users.index', compact('users'));
}
}
这是我的index.blade.php文件
@if (count($users) > 0)
@foreach($users as $user)
<li>{!! $user['first_name'] !!}</li>
@endforeach
@endif
我总是得到以下错误。因为我知道我正确地将$ user对象传递给blade.php。但我无法弄清楚出了什么问题
ErrorException in f1adbf0485f192729c60772e5dc5b16ad0234be2.php line 3:
Undefined index: first_name (View: /Users/Mac/Development/PHP/Laravel/Lara53/resources/views/admin/users/index.blade.php)
in f1adbf0485f192729c60772e5dc5b16ad0234be2.php line 3
at CompilerEngine->handleViewException(object(ErrorException), '1') in PhpEngine.php line 44
at PhpEngine->evaluatePath('/Users/Mac/Development/PHP/Laravel/Lara53/storage/framework/views/f1adbf0485f192729c60772e5dc5b16ad0234be2.php', array('__env' => object(Factory), 'app' => object(Application), 'errors' => object(ViewErrorBag), 'users' => array(array(array('first_name' => 'James', 'last_name' => 'Bond', 'location' => 'UK'), array('first_name' => 'Jimmy', 'last_name' => 'Carter', 'location' => 'USA'))))) in CompilerEngine.php line 59
at CompilerEngine->get('/Users/Mac/Development/PHP/Laravel/Lara53/resources/views/admin/users/index.blade.php', array('__env' => object(Factory), 'app' => object(Application), 'errors' => object(ViewErrorBag), 'users' => array(array(array('first_name' => 'James', 'last_name' => 'Bond', 'location' => 'UK'), array('first_name' => 'Jimmy', 'last_name' => 'Carter', 'location' => 'USA'))))) in View.php line 149
答案 0 :(得分:2)
public function index(){
$users = [
'0' => [
'first_name' => 'James',
'last_name' => 'Bond',
'location' => 'UK'
],
'1' => [
'first_name' => 'Jimmy',
'last_name' => 'Carter',
'location' => 'USA'
]
];
return view('admin.users.index', compact('users'));
}
答案 1 :(得分:1)
您使用$ users[] = array()
,因此$users[0]
保存数组。在你的刀片中应该像这样,或者实现为Paul Androschuk的回答。
@if (count($users[0]) > 0)
@foreach($users[0] as $user)
<li>{!! $user['first_name'] !!}</li>
@endforeach
@endif