简体   繁体   中英

Manipulating Model data in controller before sending to View - Laravel

I am receiving some data from my model and would like to manipulate it before sending to one of my views. The view is mainly just a javascript datagrid that will display the incoming JSON response as-is, so cannot re-format anything in the view.

My current response from the model, when sent to the view looks like this:

{
  "first_name": "Joe",
  "last_name": "Jackson",
  "nickname": "JJ",
  "salutation": "Mr",
  "city": "Oakville",
  "country": "Newland",
  "orders": "12",
  "total": "34600.00"
}

The response I would like to send to the view, needs to be reformatted in way that the view can use and display directly, without any further manipulation being done in the view eg:

{
  "Client": "Mr Joe Jackson<br>Oakville, Newland",
  "Orders": "12 Orders<br>Total Sales: $34600.00"
}

I can write a function to re-format the data, but where should I place this function and how should I access it?

FYI, Im not using blade as this is primarily for a single page JS app.

You can put a function into a Model and use it from controller, something like:

Client:: getFormattedData($id);

And in a model:

public function getFormattedData($id)
{
    ....
    return $data;
}

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