Laravel 映射到 return 单个值显示为对象,而不是字符串

Laravel map to return single value shows as object, not as string

在我看来,我正在显示一个值,但它显示为一个对象:["Jamie Rogers"]。我想删除 [" ... "] 部分。

函数:

$auditor = $audit->map(function ($user) {
    return $user->name;
});

审计的初始结构:

Collection {#432 ▼
  #items: array:1 [▼
    0 => Score {#410 ▼
      #table: "scores"
      #fillable: array:3 [▶]
      #connection: null
      #primaryKey: "id"
      #keyType: "int"
      #perPage: 15
      +incrementing: true
      +timestamps: true
      #attributes: array:9 [▶]
      #original: array:9 [▼
        "id" => 5
        "score" => 0.11
        "name" => "Jamie Rogers"
        "created_at" => null
        "updated_at" => "2017-03-19 17:47:23"
      ]
      #relations: array:1 [▶]
      #hidden: []
      #visible: []
      #appends: []
      #guarded: array:1 [▶]
      #dates: []
      #dateFormat: null
      #casts: []
      #touches: []
      #observables: []
      #with: []
      #morphClass: null
      +exists: true
      +wasRecentlyCreated: false
    }
  ]
}

如果我使用 return (string) $user->name 转换值,它不会改变它。

要获取集合的第一个(也是唯一一个)对象,请使用 pluck 方法,然后使用 first 方法:

$auditor = $audit->pluck('name')->first();

map 函数在 collection 上可用,当您在集合上映射时,这意味着您想对数据和 return 处理后的数据做一些事情,例如你现在在你的 API 中有名字和姓氏 你想以全名

回复
    $collection->map(function($value, $key) {//https://laravel.com/docs/5.4/collections#method-map
        return [
            'full_name' => $value->firstName . ' ' . $value->lastname
        ]
    });

map函数中你传递的函数会得到两个value第一个是值,第二个是key.

所以在你的情况下你也可以用这种方式

    $collection->map(function($value, $key) {
        return [
            'name' => $value->name
        ]
    })->first();

但是为了减少编码 比我更好。

pluck中你可以得到一个像array_column这样的键值,但不像 pluck 仅适用于集合。如果您传递第二个参数,您还可以告诉 pluck 方法什么是值的键,键将是该列的值。还喜欢提 pluck 也 return 一个 collection 对象。因此,您可以在该对象上使用 first 等所有方法。