Laravel 5.2 - 空数组不起作用时同步?
Laravel 5.2 - Syncing when empty array not working?
我有以下功能:
private function syncTags(Profile $profile, array $tags)
{
$profile->tags()->sync($tags);
}
我这样称呼它:
$this->syncTags($profile, $request->input('tags'));
但是抛出错误:
Argument 2 passed to syncTags() must be of the type array, null given
当我没有 select 任何标签时,就会发生这种情况。标签是用户可以 check/uncheck 的复选框列表。我该如何解决?
我试过以下方法也没有什么区别:
$profile->tags()->sync((array) $tags);
如果您有时不带任何标签调用 syncTags()
,您可以通过提供默认值使第二个参数可选:
private function syncTags(Profile $profile, array $tags = [])
这将允许您同时执行以下操作:
$obj->syncTags($profile, $tags);
还有这个:
$obj->syncTags($profile);
虽然我不太确定后者的意义是什么,因为你不会同步任何东西。 (除非如果没有提供特定标签,该方法可能会同步所有内容。)
如果你可以使用集合或请求实例就使用
$profile->tags()->sync($request->get('tags', []))
否则这样做
$profile->tags()->sync(($tags) ? $tags : [])
我有以下功能:
private function syncTags(Profile $profile, array $tags)
{
$profile->tags()->sync($tags);
}
我这样称呼它:
$this->syncTags($profile, $request->input('tags'));
但是抛出错误:
Argument 2 passed to syncTags() must be of the type array, null given
当我没有 select 任何标签时,就会发生这种情况。标签是用户可以 check/uncheck 的复选框列表。我该如何解决?
我试过以下方法也没有什么区别:
$profile->tags()->sync((array) $tags);
如果您有时不带任何标签调用 syncTags()
,您可以通过提供默认值使第二个参数可选:
private function syncTags(Profile $profile, array $tags = [])
这将允许您同时执行以下操作:
$obj->syncTags($profile, $tags);
还有这个:
$obj->syncTags($profile);
虽然我不太确定后者的意义是什么,因为你不会同步任何东西。 (除非如果没有提供特定标签,该方法可能会同步所有内容。)
如果你可以使用集合或请求实例就使用
$profile->tags()->sync($request->get('tags', []))
否则这样做
$profile->tags()->sync(($tags) ? $tags : [])