0

I'm building a CRUD using laravel and I'm not sure about the MVC rules.
I thought that all the functions related to database (Crud) should be done inside the model and not the controller. But I found this inside User's Controller:

protected function create(array $data)
{
    return User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => bcrypt($data['password']),
    ]);
}  

I know it's not persisting to the database, just returning a new instance of the class User. Should I call this function inside the model so then persist it ?
Doesn't make much sense calling this to just make a ->save().

PlayHardGoPro
  • 2,791
  • 10
  • 51
  • 90
  • it still happens inside User Model ? `User::create` – Anar Bayramov Sep 13 '17 at 01:58
  • `create` persists the data in the database. – Wreigh Sep 13 '17 at 01:59
  • And is it "ok" to do it inside the controller instead of inside Model? Why exatcly? I thought all the data "management" should happen inside Model only. – PlayHardGoPro Sep 13 '17 at 02:51
  • two related topics: [Architecture more suitable for web apps than MVC](https://stackoverflow.com/questions/7621832/architecture-more-suitable-for-web-apps-than-mvc/7622038#7622038) [How should a model be structured in MVC](https://stackoverflow.com/questions/5863870/how-should-a-model-be-structured-in-mvc) – Amin.Qarabaqi Sep 13 '17 at 05:45

1 Answers1

0

Your example is okay, but if you think your controller's doing too much work that it should not be doing, you can refactor your code to transfer the work.

For example, in your code, the password is being bcrypted, you can create a new function in User model (or another helper class if you want, like UserHelper or UserQuery)

class User ...
{
    public static function registerUser($data)
    {
        $data['password'] = bcrypt($data['password']);
        $user = self::create($data);
        return $user;
    }
}

You can now use this to directly pass user data, it will shoulder the bcrypting of the password.

$new_user = User::registerUser(['username' => 'helloworld', 'password' => 'worldhello']);

I think we should always put in mind if a class/method/any other point of control is doing something that is beyond its purpose, then that's the time we should think of refactoring it to another point of control.

Wreigh
  • 3,215
  • 16
  • 37
  • 1
    I start to question this because it's Laravel's default class. And I think it's easier ME being wrong than laravel's team. Thanks! – PlayHardGoPro Sep 13 '17 at 12:49