onurzdgn's avatar

CRUD in model

How can i creat, read, update and delete user in user model? Is it better for clean code or if I do in controller is better?

0 likes
3 replies
vincent15000's avatar
Level 63

Controllers are the entry points for the routes. A route points to a method in a controller.

A model is only to define the object, his properties, and sometimes the different queries to read, store, ... in the database. With Laravel you don't have to write any repository to query in the database, it uses Eloquent which is automatically available for each model.

So your model can often be minimalist.

In you case you need to use methods in a controller to make all the CRUD for a model.

Tray2's avatar

I would say that it is up to you where you place it.

I prefer having the code in the controller method, and since I like single action controllers, it makes sense to have the logic in the controller.

However, you can place the logic in the model, or even use a service class to do the heavy lifting, like I said it's up to you which you choose.

I would however, recommend that you use KISS as much as possible.

That being said, if you work for a company, they usually have a way of working when it comes to code placement, and patterns. Those conventions how ever insane they might seem needs to be followed.

Here is an example on how one can do show in a single action controller with route model binding.

class GamesShowController extends Controller
{
    public function __invoke(GameShowView $gameShowView)
    {
        return view('games.show')
            ->with([
                'game' => $gameShowView,
            ]);
    }
}

You are welcome to look how I done it in my Mediabase project.

https://github.com/Tray2/mediabase/tree/main

3 likes

Please or to participate in this conversation.