Answer the question
In order to leave comments, you need to log in
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'),
]);
}
}
public function saves($role)
{
Role::insert($role);
}
Answer the question
In order to leave comments, you need to log in
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.
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 questionAsk a Question
731 491 924 answers to any question