0

I'm asking myself if i'm doing things in the right way. Here is my concern :

I have my User Model like this

class User extends Model {

public function activities()
{
    return $this->hasMany('App\Activity');
}

....

public function getTotalDistanceTraveled() {
    return Step::join('activities', 'activity_id', '=', 'activities.id')->where('activities.user_id', $this->id)->sum('steps.km');
}

Is it the right place to put function like getTotalDistanceTraveled() in the User Model ? Or it should be in the Controller which generate the View ? Or do I have to create a UserRepository ?

Thanks for your recommandations

5
  • It should be in another model and then make a relations to them Commented Aug 21, 2015 at 9:36
  • There are also an Activity model and a Step model which are related together. What I want is to get the total distance of all steps travelled by a user. In which model do you recommand to put this function ? Commented Aug 21, 2015 at 9:43
  • I see. Put that in your controller now to get the returned object Commented Aug 21, 2015 at 9:46
  • As you return steps I would put it into the Step model. Would confuse me to get a instance of Step in the User model. Commented Aug 21, 2015 at 9:49
  • 2
    I would suggest you create a repository and do your math there. Then you can keep your models clean and concise. The controller is not a place for this logic. Commented Aug 21, 2015 at 9:50

1 Answer 1

2

For me it depends on the size of the app. If it's a simple app that is going to take very little maintenance and basic Eloquent queries then sure keep them in the model - what's the point in troubling yourself over a small app?

If your app is going to be constantly maintained and large in size then I would result to a Repository design, that way you keep everything organised, maintenance is easier and anybody else working on the project with yourself can find their way around relatively easier.

Personally on a large app I like to have repositories but split my more advanced, complex queries into a dedicated class for each query and remove them from the repository. This for me makes maintaining easier.

Controller wise, I personally prefer to keep my controllers 'skinny'. But a simple Eloquent query isn't going to hurt anything for example:

public function view($id) 
{
    return view('view-user')->with('user', User::find($id))
}

It ultimately depends on the scope of your app.

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.