V
V
Vasyl Fomin2016-10-21 16:18:25
Laravel
Vasyl Fomin, 2016-10-21 16:18:25

Methods for saving data in a Laravel model (DB). Which one to use?

I'm just starting to learn Laravel, and I ran into this question: which of the following methods would be more correct to use to save data to the database (model)?
In the example of saving roles for the user, but this is not so important, the same is true for articles.

class RoleController extends RootController
{
public function store(Request $request)
{
//Способ 1 saved
        $role= new Role();
        $role->name         = $request->get('name');
        $role->display_name = $request->get('display_name'); 
        $role->description  = $request->get('description'); 
        $role->save();

//Способ 2 saved
        $roleM = new Role();
        $role = $request->only(['name', 'display_name', 'description']);
        $roleM->saves($role);

//Способ 3 saved
        Role::create([
            'name' => $request->get('name'),
            'display_name' => $request->get('display_name'),
            'description' => $request->get('description'),
        ]);
}
}

For the second method, in the Role model, I created the following method, which inserts data into the database:
public function saves($role)
  {
    Role::insert($role);
  }

There is also an option to pass the processed array to the model, and there, as in method 2, create your own request.
Advise which way to use correctly.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
JhaoDa, 2016-10-21
@fomvasss

No. 1 and No. 3 are identical inside, use whichever you like best and, logically, is more suitable in a particular situation. Throw out #2.

V
Vyacheslav Plisko, 2016-10-21
@AmdY

The first way allows you to fill in fields that are not allowed in fillable
The second way is best, only the name must be given normal. For different contexts, the conservation rules may be different, so it is considered good practice to make separate constructors and persisters. As an example, at the registration stage, the user sets all the fields, but when editing the email, you cannot change it.
The third way most uses bulk filling and will not fill in fields that are not specified in the fillable. As far as I remember, there were also troubles with events, they differed from the save method, so it's better to do $user->fill($role)->save();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question