Laravel 8 有條件的合并數(shù)據(jù)

2021-07-19 11:47 更新

有些時(shí)候,你可能希望在給定條件滿足時(shí)添加多個(gè)屬性到資源響應(yīng)里。在這種情況下,你可以使用 mergeWhen 方法在給定的條件為 true 時(shí)將多個(gè)屬性添加到響應(yīng)中:

/**
 * 將資源轉(zhuǎn)換成數(shù)組
 *
 * @param  \Illuminate\Http\Request  $request
 * @return array
 */
public function toArray($request)
{
    return [
        'id' => $this->id,
        'name' => $this->name,
        'email' => $this->email,
        $this->mergeWhen(Auth::user()->isAdmin(), [
            'first-secret' => 'value',
            'second-secret' => 'value',
        ]),
        'created_at' => $this->created_at,
        'updated_at' => $this->updated_at,
    ];
} 

同理,如果給定的條件為 false 時(shí),則這些屬性將會(huì)在資源響應(yīng)被發(fā)送給客戶端之前被移除。

注意:mergeWhen 方法不應(yīng)該被使用在混合字符串和數(shù)字鍵的數(shù)組中。此外,它也不應(yīng)該被使用在不按順序排列的數(shù)字鍵的數(shù)組中。

以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)