简体   繁体   中英

Get only specific attributes with from Laravel Collection and relation

I want to remove some attributes from the final result and found this here Get only specific attributes with from Laravel Collection

This works for the top level but what is need is to remove some attributes from a related item say user has one access_card and access_card have some long text details as one of its attribute.

i want to remove that attribute from final result. Is is possible with the method mentioned in link?

Assuming you have a "code" field on access card, you can try something like that:

$users = Users::with('access_card')->get();
$subset = $users->map(function ($user) {
    return collect(
        [
            'id' => $user->id,
            'email' => $user->email,
            'access_card' => $user->access_card->code,
        ]);
});

dd($subset);
User::with(['access_card' => function($query){
    $query->select('code');
} ])->select('id', 'email')->get();

Assumig you want user id and email with an access card and only the card_code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM