Thursday, March 2, 2017

Is it better to query a database from the controller or with a model function in laraval?

So currently I am using the following code in my controller to query the database. This code checks whether a user has set their username yet.

  $user = User::where('email', $userdata['email'])->first();
    if(empty($user->username)){
      echo 'Set username here...';
    } else {
        echo 'My home page!';
    }

My question is, is it better to make a function in the User model to do this, or keep it as it is. So for example, the first line would be removed and in the if statement it would call the model function which would give true or false.

My initial thought is this should be moved to a model function as MVC structured projects should have 'fat controllers' and 'skinny models'. This is 'business logic' so should be in the model. If so, could you give an example on how I would move this to a model and call the function from the controller.



via JL9

Advertisement