Benjamin W Benjamin W - 19 days ago 8
PHP Question

Laravel place query inside of controller or model class

#1
Class controller {
$customer = Model\customer::find($id);
}

#2
Class controller {
$customer = new Model\customer;
$customer = $customer->data($id);
}

Class Model {
public function data($id) {
return self::find($id);
}
}


I'm new in larava, I got a question about MVC query.

I saw many people put query inside of controller like #1

I usually like to put query inside of model class.

any suggestion?

Answer

According to me MVC means - Model View Controller.

In a general language Model should contain the Database Query related stuffs whereas in View you should always use variables to populate view data and at last Controller is generally for catching the requests and send the response by doing some logical functionality on request.

<?php 

namespace App\Models;

class ExampleModel
{
    // All the database related methods like - all, paginate, find, where, etc would goes in the model...
}

In case of Views

<html>
  ...
  YOUR_CONTENT_HERE
  ...
</html>

and in case of Controller,

<?php 

namespace App\Controllers;

class ExampleController
{
    public function index()
    {
       $request = request()->all();
       ... do some logical work here ...
       return response($data);
    }
}

Thats what MVC code structure would be like - in my opinion

Hope this helps!