[英]Undefined variable in laravel blade partial view error
I am getting the following error when loading a page: Undefined variable: userIds
加载页面时出现以下错误: Undefined variable: userIds
However, the variavle is reaching the partial given when I try {{ isset($userIds) ? 'Yes' : 'No' }}
但是,当我尝试{{ isset($userIds) ? 'Yes' : 'No' }}
{{ isset($userIds) ? 'Yes' : 'No' }}
it returns 'Yes' when the block of code is reached. {{ isset($userIds) ? 'Yes' : 'No' }}
当到达代码块时它返回 'Yes'。
The error occurs with the variable $userIds in the following input type:以下输入类型中的变量 $userIds 发生错误:
</li>
@foreach ($users as $index => $user)
<li class="list-group-item"
style="{{ (isset($usersFiltered) && is_array($usersFiltered) && !in_array($user->id, $usersFiltered) ) ?
'display: none;' : ''}}">
<div class="checkbox">
<label>
<input type="checkbox" class="awe-selectable" id="users[{{ $index }}]" name="users[{{ $index }}]"
value="{{ $user->id }}" {{ in_array($user->id,$userIds) ? 'checked' : '' }}>
<label for="users[{{ $index }}]">{{ $user->name }}</label>
</label>
</div>
</li>
@endforeach
My controller code sending the variable to the partial:我的控制器代码将变量发送到部分:
return view('core::admin.groups.partials._users_form', [
'group' => $group,
'users' => $users,
'usersFiltered' => $usersFiltered,
'userIds' => $userIds,
]);
Is it a syntax mistake?是语法错误吗? If I replace $userIds by any of the other variables, those too will return the same "undefined" error (fe with $usersFiltered)如果我用任何其他变量替换 $userIds,这些变量也会返回相同的“未定义”错误(fe with $usersFiltered)
Thanks in advance, will edit the post with more information as needed.提前致谢,将根据需要编辑帖子并提供更多信息。
the syntax looks good to me, but I would suggest to you to do this:语法对我来说看起来不错,但我建议你这样做:
// in your controller
foreach ($users as $user) {
$user->checked = false;
if ((is_array($userIds) and !empty($userIds)) and in_array($user->id, $userIds)) {
$user->checked = true;
}
}
now there is no need to send the $userIds
to the view, since you fixed it in the controller.现在不需要将$userIds
发送到视图,因为您在控制器中修复了它。
// in your view
<input type="checkbox" class="awe-selectable" id="users[{{ $index }}]" name="users[{{ $index }}]" value="{{ $user->id }}" {{ ($user->checked) ? 'checked' : '' }}>
Happy coding!快乐编码!
Solved!解决了!
The issue was that when the page was rendered, the variable was not defined in the main page render (/create), only in the method that rendered the partial, so when I was opening the main window, the variable was not yet defined because it was only received from the controller once a filter was applied.问题是页面渲染的时候,变量没有在主页面渲染(/create)中定义,只有在渲染部分的方法中,所以当我打开主窗口时,变量还没有定义,因为它仅在应用过滤器后才从控制器接收。
Sollution:解决方案:
/**
* GET: /admin/security/groups/create
*/
public function create()
{
**$userIds = !empty($request['userIds']) ? $request['userIds'] : [];**
(...) (……)
return view('core::admin.groups.create', [
'group' => new Group,
**'userIds' => $userIds,**
'users' => $users,
'isCreating' => true,
]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.