Laravel 5中all()和toArray()之间的区别

Jul*_*oro 8 arrays collections laravel

当我管理我需要转换为数组的集合时,我通常会使用toArray().但我也可以使用all().我不知道这两个功能的差异......

有人知道吗?

cma*_*mac 14

如果它是Eloquent模型的集合,模型也将使用toArray()转换为数组

    $col->toArray();
Run Code Online (Sandbox Code Playgroud)

总而言之,它将返回一个Eloquent模型数组,而无需将它们转换为数组.

    $col->all();
Run Code Online (Sandbox Code Playgroud)

toArray方法将集合转换为普通的PHP数组.如果集合的值是Eloquent模型,模型也将转换为数组: toArray()

all()返回集合中的项目

/**
 * Get all of the items in the collection.
 *
 * @return array
 */
public function all()
{
    return $this->items;
}
Run Code Online (Sandbox Code Playgroud)

toArray()返回集合的项目,如果是Arrayable则将它们转换为数组:

/**
 * Get the collection of items as a plain array.
 *
 * @return array
 */
public function toArray()
{
    return array_map(function ($value) {
        return $value instanceof Arrayable ? $value->toArray() : $value;
    }, $this->items);
}
Run Code Online (Sandbox Code Playgroud)

例如:从数据库中抓取所有用户,如下所示:

$users = User::all();
Run Code Online (Sandbox Code Playgroud)

然后将它们单向倾倒,你会发现不同之处:

dd($users->all());
Run Code Online (Sandbox Code Playgroud)

并使用toArray()

dd($users->toArray());
Run Code Online (Sandbox Code Playgroud)

  • @s3c 在版本 7-9 中,功能没有改变。`toArray()` 的逻辑还将嵌套对象转换为数组。 (2认同)