0

In controller get data from db like this, I want to pass whole of $request to another function in this controller to get price it calculating price based of many things from $request:

$user = Auth::user();
$query = Post::query();

$query
->where('province', '=', $user->province)
->where('city', '=', $user->city);

$customers = $query->get();
$customers['calculator'] = $this->calculator($request); // call function

my problem is it return like this:

{
  "0": {
    "id": 1,
    "hash": "RqH29tkfm1dwGrXp4ZCV",
  },
  "1": {
    "id": 3,
    "hash": "RqH29tkfm1dwGsXp4ZCV",
  },
  "calculator": {
    "price": 1
  }
}

But I need to use that function for each data, and result should be like this:

{
  "0": {
    "id": 1,
    "hash": "RqH29tkfm1dwGrXp4ZCV",
    "calculator": {
      "price": 1
    }
  },
  "1": {
    "id": 3,
    "hash": "RqH29tkfm1dwGsXp4ZCV",
    "calculator": {
      "price": 1
    }
  }
}
1
  • If you want calculator assigned to each Customer, you need to use a loop. Commented Dec 12, 2019 at 18:39

1 Answer 1

1

What you want is to set a calculator key for each item in the $customers collection. So you need to loop over it:

foreach ($customers as $customer) {
    $customer->calculator = $this->calculator($request);
}

Notice that since the $customer is a Model you should set the calculator as a property. Internally it will be set to the attributes array.

Sign up to request clarification or add additional context in comments.

Comments

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.