Currently I am using the following code in my controller to query the database. This code checks whether a user has set their username yet.
$user = User::where('email', $userdata['email'])->first();
if(empty($user->username)){
echo 'Set username here...';
} else {
echo 'My home page!';
}
My question is, is it better to make a function in the User model to do this, or keep it as it is. So for example, the first line would be removed and in the if statement it would call the model function which would give true or false.
My initial thought is this should be moved to a model function as MVC structured projects should have 'fat models' and 'skinny controllers'. This is 'business logic' so should be in the model. If so, could you give an example on how I would move this to a model and call the function from the controller.
You should definitely move all data related code to the model. You've asked for an example. I'd create this method in a model:
public function findByEmail($email)
{
return $this->where('email', $email)->first();
}
In the controller:
use App\User;
protected $user;
public function __construct(User $user)
{
$this->user = $user;
}
public function showSomething($userdata)
{
return view('some.view', [
'user' => $this->user->findByEmail($userdata['email'])
]);
}
In a view:
{{ empty($user->username) ? 'Hello anonymous' : $user->username }}
In this example, it looks like moving query in the model is not very good idea, but when your application will grow you'll see this is the only good way to work with data. It's MVC. Also, you should keep validation logic in the Request classes, business logic in their own classes etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With