1

The following:

Customer::with('tickets:customer_id,subject')->get();

returns the following:

[
  {
    "id": 1,
    "company": "Test Ltd",
    "support": "Standard",
    "tickets": [
      {
        "customer_id": "1",
        "name": "Test ticket 1"
      },
      {
        "customer_id": "1",
        "name": "Test ticket 2"
      }
    ]
  }
]

How can I flatten the related field, tickets to get:

tickets: ["Test ticket 1", "Test ticket 2"]

I tried doing a ->flatten() after ->get() but that didn't work at all.

It feels like it should be something simple that I'm missing and just can't find in the docs or by googling (thanks for the word with, that screws pretty much all sane results).

1 Answer 1

3

I haven't tested this out but using ->map() might help you in this instance:

$customers = Customer::with('tickets:customer_id,name')
    ->get()
    ->map(function($customer, $key) {
        $customer->tickets = $customer->tickets->pluck('name')->all();
        return $customer;
    })->all();

->pluck() will return only the value of the key specified.

Update

This can be achieved by running a query within map and avoiding eager loading:

$customers = Customer::all()
    ->map(function($customer, $key) {
        $customer['tickets'] = $customer->tickets()->get()->pluck('name')->all();
        return $customer;
    })->all();
Sign up to request clarification or add additional context in comments.

2 Comments

map() was the answer, however Laravel doesn't allow me to assign over the existing property, so instead of $customer->tickets = I did $customer->TTs = and then hid the tickets with ->withHide('tickets') on the return. Thanks!
Thats understandable. Alternatively, you could avoid eager loading tickets and run a new query within the ->map() settings $customer['tickets']. Thats only if you want to avoid hiding tickets after the map.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.