panthro
panthro

Reputation: 24061

Where to operate on data?

My controller calls a repository which gets data from a model, this is then returned up the chain to the controller, which outputs the data in a view.

Where should I operate on this data? For example, perhaps I wish to add a random object to the data:

//Controller
$data = $this->repository->getAllRows();

Where should this go? in the controller? in the eloquent repository?

$data->splice(0, 5, [$myNewObject]);

Upvotes: 0

Views: 77

Answers (2)

Fabio Antunes
Fabio Antunes

Reputation: 22862

It depends, but generally I like to keep my models clean without any logic.

Now if that is a single action, just do it in the controller.

If it's a common task and you want to share it along other controllers, you have two options:

  • Creating a class so you can use that functionality sometimes inside your controllers
  • Creating a controller with your operating data functions and extending all of your controllers from it.

I usually adopt this last one, specially when creating API's where I want to create filters to hide some data.

EDIT

This is a screenshot with a structure that I used for my last project named Paka: enter image description here

Upvotes: 1

Bishal Paudel
Bishal Paudel

Reputation: 1946

Depends on what you are doing it for. If its directly related to data, you can place it in model, or its directly related to logic, keep it on controller. Like you can keep it on model if you need like:

//on model
function getRecentRows()
{
    $data = .....
    return $data->splice(0, 5, [$myNewObject]);
}

You will keep this on controller if

//on controller
$data = $this->repository->getAllRows();
$data->splice(0, 5, [$myNewObject]);
$datas->each(function($item){
    $item->is_featured = true;
});
//return view with data

This might not be the exact answer. You have to provide exact case here.

Upvotes: 1

Related Questions