Home > Mobile >  "flatten" collection "With('model')"
"flatten" collection "With('model')"

Time:02-04

I've been trying to get my head around this for a while, tried flatten, map, and a bunch of other things in "https://laravel.com/docs/8.x/collections" but nothing seems to work.

Other than doing a foreach and creating a new array (which is super sub-optimal); there has to be a better way...right?

Note: I've read all the answers on similar issues, nothing works

Heres my query:

$users = User::where('active',1)
    ->whereHas('role', function ($query) use ($column, $role){
            $query->where('role_'.$column, $role);
    })
    ->with('role:id,role_name,role_category')
    ->orderBy('users.id')
    ->get([
        'id',
        'email',
        'phone_number',
        'id_role',
        'firstname',
        'lastname',
        'verified',
        'active',
        'id_configuration',
        'external_service_id',
    ]);

I'm getting this output:

[{
    "id": 968,
    "email": "[email protected]",
    "phone_number": "123",
    "id_role": 4,
    "firstname": "Name",
    "lastname": "TEST User",
    "verified": 0,
    "active": 1,
    "id_configuration": 1,
    "external_service_id": 123,
    "role": {
        "id": 4,
        "role_name": "Admin",
        "role_category": "Company"
    }
}]

But the output I need to return is this:

[{

    "id": 968,
    "email": "[email protected]",
    "phone_number": "12312",
    "id_role": 4,
    "firstname": "Admin",
    "lastname": "TEST User",
    "verified": 0,
    "active": 1,
    "id_configuration": 1,
    "external_service_id": 123,
    "role_name": "Admin",
    "role_category": "Company"
}]

CodePudding user response:

You could use a mutator to add these properties to the model https://laravel.com/docs/8.x/eloquent-mutators

Assuming each user only has one role, then in the User model add

    public function getRoleNameAttribute($value)
    {
        return $this->role->role_name;
    }

If this property is always required then you can add an appends property to the User model https://laravel.com/docs/8.x/eloquent-serialization#appending-values-to-json

protected $appends = ['role_name'];

If not, then you can use append when returning the model https://laravel.com/docs/8.x/eloquent-serialization#appending-at-run-time

return $user->append('role_name')->toArray();
  •  Tags:  
  • Related