Codementor Events

Working With Thin Controller And Fat Model Concept In Laravel

Published Oct 01, 2018

Models and controllers are one of most essential programming handlers in the Laravel MVC framework, and both are used vastly for different functional operations. Models in Laravel are created inside the app folder and are mostly used to interact with the database using Eloquent ORM, while the controllers are located inside the directory App/Http/Controllers.

As a programmer, you should have the knowledge how to keep the balance in between the programming usage of Models and controllers and which one should be more utilized for alloting functional tasks.As which one should be more utilized for alloting functional tasks in applications deployed on any PHP MySQL hosting.

What is the Concept of Thin Controller and FAT Models

The concept of thin controller and fat model is that we do less work in our controllers and more work in our models. Like we use our controllers to validate our data and then pass it to the models. While in models, we define our actual functional logic and main coding operations of the desired application. This code structuring process is also a very basic concept of MVC and also the differentiating factor from the conventional complex programming which we mistakenly ignore sometimes.

Why FAT Controllers Are Bad For Handling Code

Controllers are always meant to be defined short and concise, and it should only be used for receiving requests and return responses to it. Anything else further should be programmed in Models, which is actually made for main functional operations.
Placing functional logics in controllers can be bad for many reasons, as it not only makes code structure long but also makes it complex sometimes. Further placing code in Controllers is also not recommended because if same functionality is needed somewhere else in route, then pulling out the whole code from their becomes difficult and so its reusability in the application.

Though Laravel is a MVC framework but while developing on laravel, we sometimes ignore this and write mostly all our code including the extending of App\Model and all our functional logic in controller route methods. What we can do here is we can create a sub model of our parent model. For example, our parent model is User then we can create another sub model of user name in CustomerModel if you are using the same User model for all types of users. In this model we will write all the logics related to user type Customer.

So now let’s take an example of my existing blog creating comment system with laravel and vuejs. In that article, you can see I have made so much mess in my controller methods. Mostly, I have written all my comments logic in my methods, so to shorten that let’s clean them in this article. Inside app folder I will create a new file with name CommentModel.php. Inside this file, I will write my whole logic for comment functions. This is my basic file:

<?php
namespace App;

use App\Comment;
use App\CommentVote;
use App\CommentSpam;
use App\User;
use Auth;


class CommentModel
{
  
}

?>

Right now it contains no function but have the reference of all my models which I required for this model. Let’s first add a function named getallcomments passing $pageId as a parameter inside it. The function will get all the comments for the given page:

public function getAllComments($pageId)
   {
       $comments = Comment::where('page_id',$pageId)->get();

       $commentsData = [];
      
       foreach ($comments as $key) {
           $user = User::find($key->users_id);
           $name = $user->name;
           $replies = $this->replies($key->id);
           $photo = $user->first()->photo_url;
           // dd($photo->photo_url);
           $reply = 0;
           $vote = 0;
           $voteStatus = 0;
           $spam = 0;
           if(Auth::user()){
               $voteByUser = CommentVote::where('comment_id',$key->id)->where('user_id',Auth::user()->id)->first();
               $spamComment = CommentSpam::where('comment_id',$key->id)->where('user_id',Auth::user()->id)->first();
              
               if($voteByUser){
                   $vote = 1;
                   $voteStatus = $voteByUser->vote;
               }

               if($spamComment){
                   $spam = 1;
               }
           }
          
           if(sizeof($replies) > 0){
               $reply = 1;
           }

           if(!$spam){
               array_push($commentsData,[
                   "name" => $name,
                   "photo_url" => (string)$photo,
                   "commentid" => $key->id,
                   "comment" => $key->comment,
                   "votes" => $key->votes,
                   "reply" => $reply,
                   "votedByUser" =>$vote,
                   "vote" =>$voteStatus,
                   "spam" => $spam,
                   "replies" => $replies,
                   "date" => $key->created_at->toDateTimeString()
               ]);
           }   
          
       }
       $collection = collect($commentsData);
       return $collection->sortBy('votes');
   }

Now i will create another function named replies which takes $commentId as a parameter. The function is more or less programmed in the same manner as the upper function get all comments.

protected function replies($commentId)
   {
       $comments = Comment::where('reply_id',$commentId)->get();
       $replies = [];
      

       foreach ($comments as $key) {
           $user = User::find($key->users_id);
           $name = $user->name;
           $photo = $user->first()->photo_url;

           $vote = 0;
           $voteStatus = 0;
           $spam = 0;   
          
           if(Auth::user()){
               $voteByUser = CommentVote::where('comment_id',$key->id)->where('user_id',Auth::user()->id)->first();
               $spamComment = CommentSpam::where('comment_id',$key->id)->where('user_id',Auth::user()->id)->first();

               if($voteByUser){
                   $vote = 1;
                   $voteStatus = $voteByUser->vote;
               }

               if($spamComment){
                   $spam = 1;
               }
           }
           if(!$spam){
              
               array_push($replies,[
                   "name" => $name,
                   "photo_url" => $photo,
                   "commentid" => $key->id,
                   "comment" => $key->comment,
                   "votes" => $key->votes,
                   "votedByUser" => $vote,
                   "vote" => $voteStatus,
                   "spam" => $spam,
                   "date" => $key->created_at->toDateTimeString()
               ]);
           }
          
      
       }
      
       $collection = collect($replies);
       return $collection->sortBy('votes');
   }

Now lets create a function create comment which passes $array as a parameter in it:

public function createComment($arary)
   {
       $comment = Comment::create($array);
       
       if($comment)
           return [ "status" => "true","commentId" => $comment->id ];
       else
           return [ "status" => "false" ];   
   }

Similarly, Now I will create all the function for comment in my CommentModel, so that all the functions gets accumulated in one model.

<?php
namespace App;

use App\Comment;
use App\CommentSpam;
use App\CommentVote;
use App\User;
use Auth;

class CommentModel
{
   public function getAllComments($pageId)
   {
       $comments = Comment::where('page_id', $pageId)->get();

       $commentsData = [];

       foreach ($comments as $key) {
           $user = User::find($key->users_id);
           $name = $user->name;
           $replies = $this->replies($key->id);
           $photo = $user->first()->photo_url;
           // dd($photo->photo_url);
           $reply = 0;
           $vote = 0;
           $voteStatus = 0;
           $spam = 0;
           if (Auth::user()) {
               $voteByUser = CommentVote::where('comment_id', $key->id)->where('user_id', Auth::user()->id)->first();
               $spamComment = CommentSpam::where('comment_id', $key->id)->where('user_id', Auth::user()->id)->first();

               if ($voteByUser) {
                   $vote = 1;
                   $voteStatus = $voteByUser->vote;
               }

               if ($spamComment) {
                   $spam = 1;
               }
           }

           if (sizeof($replies) > 0) {
               $reply = 1;
           }

           if (!$spam) {
               array_push($commentsData, [
                   "name" => $name,
                   "photo_url" => (string) $photo,
                   "commentid" => $key->id,
                   "comment" => $key->comment,
                   "votes" => $key->votes,
                   "reply" => $reply,
                   "votedByUser" => $vote,
                   "vote" => $voteStatus,
                   "spam" => $spam,
                   "replies" => $replies,
                   "date" => $key->created_at->toDateTimeString(),
               ]);
           }

       }
       $collection = collect($commentsData);
       return $collection->sortBy('votes');
   }

   protected function replies($commentId)
   {
       $comments = Comment::where('reply_id', $commentId)->get();
       $replies = [];

       foreach ($comments as $key) {
           $user = User::find($key->users_id);
           $name = $user->name;
           $photo = $user->first()->photo_url;

           $vote = 0;
           $voteStatus = 0;
           $spam = 0;

           if (Auth::user()) {
               $voteByUser = CommentVote::where('comment_id', $key->id)->where('user_id', Auth::user()->id)->first();
               $spamComment = CommentSpam::where('comment_id', $key->id)->where('user_id', Auth::user()->id)->first();

               if ($voteByUser) {
                   $vote = 1;
                   $voteStatus = $voteByUser->vote;
               }

               if ($spamComment) {
                   $spam = 1;
               }
           }
           if (!$spam) {

               array_push($replies, [
                   "name" => $name,
                   "photo_url" => $photo,
                   "commentid" => $key->id,
                   "comment" => $key->comment,
                   "votes" => $key->votes,
                   "votedByUser" => $vote,
                   "vote" => $voteStatus,
                   "spam" => $spam,
                   "date" => $key->created_at->toDateTimeString(),
               ]);
           }

       }

       $collection = collect($replies);
       return $collection->sortBy('votes');
   }

   public function createComment($arary)
   {
       $comment = Comment::create($array);

       if ($comment) {
           return ["status" => "true", "commentId" => $comment->id];
       } else {
           return ["status" => "false"];
       }

   }

   public function voteComment($commentId, $array)
   {
       $comments = Comment::find($commentId);
       $data = [
           "comment_id" => $commentId,
           'vote' => $array->vote,
           'user_id' => $array->users_id,
       ];

       if ($array->vote == "up") {
           $comment = $comments->first();
           $vote = $comment->votes;
           $vote++;
           $comments->votes = $vote;
           $comments->save();
       }

       if ($array->vote == "down") {
           $comment = $comments->first();
           $vote = $comment->votes;
           $vote--;
           $comments->votes = $vote;
           $comments->save();
       }

       if (CommentVote::create($data)) {
           return true;
       }

   }

   public function spamComment($commentId, $array)
   {
       $comments = Comment::find($commentId);

       $comment = $comments->first();
       $spam = $comment->spam;
       $spam++;
       $comments->spam = $spam;
       $comments->save();

       $data = [
           "comment_id" => $commentId,
           'user_id' => $array->users_id,
       ];

       if (CommentSpam::create($data)) {
           return true;
       }

   }
}
?>

Now we have all our required methods in CommentModel. So now let’s clean up CommentController which is currently bit complex and lengthy in code structure. As right now CommentController look like this:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Comment;
use App\CommentVote;
use App\CommentSpam;
use App\User;
use Auth;

class CommentController extends Controller
{
  
   /**
    * Get Comments for pageId
    *
    * @return Comments
    */
   public function index($pageId)
   {
       //
       $comments = Comment::where('page_id',$pageId)->get();

       $commentsData = [];
      
      
       foreach ($comments as $key) {
           $user = User::find($key->users_id);
           $name = $user->name;
           $replies = $this->replies($key->id);
           $photo = $user->first()->photo_url;
           // dd($photo->photo_url);
           $reply = 0;
           $vote = 0;
           $voteStatus = 0;
           $spam = 0;
           if(Auth::user()){
               $voteByUser = CommentVote::where('comment_id',$key->id)->where('user_id',Auth::user()->id)->first();
               $spamComment = CommentSpam::where('comment_id',$key->id)->where('user_id',Auth::user()->id)->first();
              
               if($voteByUser){
                   $vote = 1;
                   $voteStatus = $voteByUser->vote;
               }

               if($spamComment){
                   $spam = 1;
               }
           }
          
           if(sizeof($replies) > 0){
               $reply = 1;
           }

           if(!$spam){
               array_push($commentsData,[
                   "name" => $name,
                   "photo_url" => (string)$photo,
                   "commentid" => $key->id,
                   "comment" => $key->comment,
                   "votes" => $key->votes,
                   "reply" => $reply,
                   "votedByUser" =>$vote,
                   "vote" =>$voteStatus,
                   "spam" => $spam,
                   "replies" => $replies,
                   "date" => $key->created_at->toDateTimeString()
               ]);
           }   
          
       }
       $collection = collect($commentsData);
       return $collection->sortBy('votes');
   }

   protected function replies($commentId)
   {
       $comments = Comment::where('reply_id',$commentId)->get();
       $replies = [];
      

       foreach ($comments as $key) {
           $user = User::find($key->users_id);
           $name = $user->name;
           $photo = $user->first()->photo_url;

           $vote = 0;
           $voteStatus = 0;
           $spam = 0;   
          
           if(Auth::user()){
               $voteByUser = CommentVote::where('comment_id',$key->id)->where('user_id',Auth::user()->id)->first();
               $spamComment = CommentSpam::where('comment_id',$key->id)->where('user_id',Auth::user()->id)->first();

               if($voteByUser){
                   $vote = 1;
                   $voteStatus = $voteByUser->vote;
               }

               if($spamComment){
                   $spam = 1;
               }
           }
           if(!$spam){
              
               array_push($replies,[
                   "name" => $name,
                   "photo_url" => $photo,
                   "commentid" => $key->id,
                   "comment" => $key->comment,
                   "votes" => $key->votes,
                   "votedByUser" => $vote,
                   "vote" => $voteStatus,
                   "spam" => $spam,
                   "date" => $key->created_at->toDateTimeString()
               ]);
           }
          
      
       }
      
       $collection = collect($replies);
       return $collection->sortBy('votes');
   }

   /**
    * Store a newly created resource in storage.
    *
    * @param  \Illuminate\Http\Request  $request
    * @return \Illuminate\Http\Response
    */
   public function store(Request $request)
   {
       $this->validate($request, [
       'comment' => 'required',
       'reply_id' => 'filled',
       'page_id' => 'filled',
       'users_id' => 'required',
       ]);
       $comment = Comment::create($request->all());
       // dd($comment);
       if($comment)
           return [ "status" => "true","commentId" => $comment->id ];
   }

   /**
    * Update the specified resource in storage.
    *
    * @param  \Illuminate\Http\Request  $request
    * @param  $commentId
    * @param  $type
    * @return \Illuminate\Http\Response
    */
   public function update(Request $request, $commentId,$type)
   {
       if($type == "vote"){
          
           $this->validate($request, [
           'vote' => 'required',
           'users_id' => 'required',
           ]);

           $comments = Comment::find($commentId);
           $data = [
               "comment_id" => $commentId,
               'vote' => $request->vote,
               'user_id' => $request->users_id,
           ];

           if($request->vote == "up"){
               $comment = $comments->first();
               $vote = $comment->votes;
               $vote++;
               $comments->votes = $vote;
               $comments->save();
           }

           if($request->vote == "down"){
               $comment = $comments->first();
               $vote = $comment->votes;
               $vote--;
               $comments->votes = $vote;
               $comments->save();
           }

           if(CommentVote::create($data))
               return "true";
       }

       if($type == "spam"){
          
           $this->validate($request, [
               'users_id' => 'required',
           ]);

           $comments = Comment::find($commentId);
          
           $comment = $comments->first();
           $spam = $comment->spam;
           $spam++;
           $comments->spam = $spam;
           $comments->save();

           $data = [
               "comment_id" => $commentId,
               'user_id' => $request->users_id,
           ];

           if(CommentSpam::create($data))
               return "true";
       }
   }

   /**
    * Remove the specified resource from storage.
    *
    * @param  int  $id
    * @return \Illuminate\Http\Response
    */
   public function destroy($id)
   {
       //
   }
}?>

After cleaning up the controller it will look much simpler and easy to understand like this:

<?php

namespace App\Http\Controllers;

use App\CommentModel;
use Illuminate\Http\Request;

class CommentController extends Controller
{

   private $commentModel = null;
   private function __construct()
   {
       $this->commentModel = new CommentModel();
   }

   /**
    * Get Comments for pageId
    *
    * @return Comments
    */
   public function index($pageId)
   {
       return $this->commentModel->getAllComments($pageId);
   }

   /**
    * Store a newly created resource in storage.
    *
    * @param  \Illuminate\Http\Request  $request
    * @return \Illuminate\Http\Response
    */
   public function store(Request $request)
   {
       $this->validate($request, [
           'comment' => 'required',
           'reply_id' => 'filled',
           'page_id' => 'filled',
           'users_id' => 'required',
       ]);
       return $this->commentModel->createComment($request->all());
   }

   /**
    * Update the specified resource in storage.
    *
    * @param  \Illuminate\Http\Request  $request
    * @param  $commentId
    * @param  $type
    * @return \Illuminate\Http\Response
    */
   public function update(Request $request, $commentId, $type)
   {
       if ($type == "vote") {

           $this->validate($request, [
               'vote' => 'required',
               'users_id' => 'required',
           ]);

           return $this->commentModel->voteComment($commentId, $request->all());
       }

       if ($type == "spam") {

           $this->validate($request, [
               'users_id' => 'required',
           ]);

           return $this->commentModel->spamComment($commentId, $request->all());
       }
   }

}
?>

Wrap Up!

So Isn’t it looking much cleaner and simpler to understand now? This is what actually a thin controller and fat model looks like. We have all our logic related to Comment system programmed in our CommentModel and our controller is now just used to transfer data from user to our model and returning the response which is coming from our model.

So this is how structuring of thin controller and fat model is made. Give your thoughts in the comments below.

Discover and read more posts from pardeep kumar
get started
post commentsBe the first to share your opinion
Ferran Muñoz
4 years ago

Sorry but I disagree for this. The model is the entity representation and only needs the fields and relationships, no more. If you want to do logic business, you must operate with repository pattern or service pattern, it’s more clean than this :)

Arslan Ali
4 years ago

Pardeep thanks for sharing this article. I have concern that model created in constructor is an empty object and we are using it for calling methods. Its not maintaining any state of its properties. Even if calling spamComment method then function is taking commentId as input parameter. However commentId can be state of comment model.

creating object here is waste of memory if we are not using any state of that object. Please share your thoughts on it

Rishabh Pandey
5 years ago

Thanks for sharing this. I do have one question/concern to discuss.

The controller is a lot cleaner but now the model is kinda harder to maintain, when adding new functionality we’ll probably make the model worse. What are your thoughts on this?

Show more replies