Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it better to query a database from the controller or with a model function in laravel?

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.

like image 977
JL9 Avatar asked Oct 24 '25 12:10

JL9


1 Answers

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.

like image 50
Alexey Mezenin Avatar answered Oct 26 '25 04:10

Alexey Mezenin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!