natepisarski
2 months ago
153
6
Laravel

How "smart" should Model methods be?

Posted 2 months ago by natepisarski

TL;DR: Should eloquent Models look up the current request, or currently logged-in user? Or controllers

I'm really in need of some feedback on an architectural problem I've run into. I'm newer than most to Laravel, so I'm not convinced that applying the solution that C# / Node frameworks use is the right call here.

The Exact Problem

In the system, there are two kinds of users. There are Administrators and Users. Each type of user has its own model, and own table. So user.id = 1 and administrator.id = 1 are completely separate entities. This is unavoidable and cannot be made into one table, or polymorphic.

We have a function that both can use (let's say "post a question" to a "forum"). So, we have a Forum model with a post method, that takes the parameters for a new post. This would be called from the [email protected]($forUserId), and [email protected]().

We need the Administrator / User ID in the FORUM model's post. This is where I need direction - how exactly should this ID get into the function?

The approaches

Amongst the team, many things have been suggested. They are:

Use the auth() helper in the model

How it's currently implemented is post itself (in the model) calls auth() and gets the ID from that. This is the most simple method because post() doesn't need any extra parameters.

This is causing a problem because Administrators can post for other Users. This means that auth() pulls the administrator's ID, not the user they're making the post for.

Add $user or $userId as a parameter of post

This is my personal choice. The controller simply gets the user ID and passes it into the post method as a parameter. My opinion is the helper being called in the controller is more in line with MVC, and will make it easier to test (whenever we get time for tests :-) ).

However, this has the drawback of every controller needing to have the same code to pass in the user.

What I want to know

  • Does pulling the authenticated User/Administrator or the current Request in an eloquent Model break MVC? Is it an architectural anti-pattern?
  • Which of these two approaches would you take?
  • Are there any more benefits that I didn't list, one way or the other?

Please sign in or create an account to participate in this conversation.