SPONSORS

2162 views · 154 days ago

![Working With Thin Controller And Fat Model Concept In Laravel](https://images.ctfassets.net/vzl5fkwyme3u/18L41PfcrcYYkM0qAsCous/7caca26b8cfb5a643d8cb16b14ae5eae/AdobeStock_147870533.jpeg?w=1000)

Models and controllers are one of the 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. As which one should be more utilized for allowing functional tasks in applications deployed on any [PHP MySQL hosting](https://www.cloudways.com/en/php-cloud-hosting.php).

## What is the Concept of Thin Controller and FAT Models

The concept of the 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 logic in controllers can be bad for many reasons for your applications deployed on any _hosting for PHP_. 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 an MVC framework 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 username in CustomerModel if you are using the same User model for all types of users. In this model, we will write all the logic 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

<?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 has 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:

```php

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.

```php

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:

```php

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

<?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

<?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

<?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 the user to our model and returning the response which is coming from our model.

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

SPONSORS