0

Lets say I created a custom function called activateAuction should I put the function in my controller or in my model. If I put it in the controller, I will be writing the entire function in the controller. If I put the function in the model, I will call my function from my controller. Which is the right way as I want to write clean code?

tereško
  • 58,060
  • 25
  • 98
  • 150
Noah Skull Weijian
  • 129
  • 1
  • 2
  • 8
  • there are conventions but ultimately any question that asks "which is the right way ... I want clean code" is going to be opinion based. there is no right or wrong when it comes to writing code, only what works and what does not. that said, I keep the database stuff in the model. your button click will likely send a request to the controller, which will in turn pass on the request to the model for processing. that's based on some assumptions I made about your design since you didn't give us much. – But those new buttons though.. Apr 03 '19 at 01:57
  • Is it business logic? Or does it have to due directly with the response to the request. Controllers are the glue between the View/Request-Response and the business logic of your application. – ArtisticPhoenix Apr 03 '19 at 02:09

3 Answers3

0

Controllers receive a Request and return a Response. That's their only job. Keep them skinny. Skinny controllers and fat models. I don't know what activateAuction does. Maybe it should be in a Repository.

keyboardSmasher
  • 2,661
  • 18
  • 20
0

For sure you don't have to place it in the controller, keep it in the model or consider using the repository pattern, it will keep your code clean.

0

Controller should only be responsible for receiving a request and responding. It would validate and transform the request to pass the params to the function somewhere in your code.

You can either use Repository Pattern or just put in the Model.

You can start on writing your code in Controller, but when you find it verbose or code is getting repetitive. You can refactor your code and make them a function, then call the function in your Controller.

Example:


class UserController {
  ...

  public function eatCake(Request $request, Cake $cake) {

    // Validate Request
    $data = $this->validate($request, [
      'portion' => 'required|numeric',
    ]);

    // pass params
    Auth()->user()->eat($cake, $data['portion']);

    // Respond to user
    return response('OK');
  }
}

class User extends Authenticatable {
  ...
  public function eat(Cake $cake, $portion) : Consume
  {
    // Your logic
    return $this->consumes()->create([
      'cake_id' => $cake_id,
      'portion' => $portion
    ]);
  }
}
Cloud Soh Jun Fu
  • 1,456
  • 9
  • 12