laravel 5.5 best way to create data

Viewed 4806

I have a codes for create new data, but im comfuse what is the best way to insert new data in database using laravel 5.5.

Codes 1:

$user = User::create([
    'name' =>  $request->name,
    'username' => $request->username,
    'email' => $request->email,
    'password' => $request->password,
]);

or

COdes 2 :

$user = new User();
$user->name = $request->name;
$user->username = $request->username;
$user->email = $request->email;
$user->password = $request->password;
$user->save();

what is the best way ? and what is your reason?

3 Answers

They both happen to be the same. The first option is an Eloquent way of doing the second option. Eloquent is meant for things like simplifying the statement in a readable way. A method like firstOrCreate is an example of where the Eloquent way is much more readable and simple in your code. But the two you provided are basically identical.

As a side note, if you ever need to conditionally save a property, the second option allows you to use if statements, or any conditional code statements..

The two ways are good. What you need to know is when you use one or other option.

You can use mass-assign way when you want to receive and store all request data without any treatment. But you can choose the second way when you want to have a better control over the date.

E.g

You have a subscription form that receive the subscriber data including username and password, but you need encrypt the password value. In this case the best choice is the second one, because you will receive the password attribute via request, then will need encrypt the value and at end you'll set the encrypted password to $model->password attribute.

Any other case that you don't need have a absolutely control about the properties you can use mass-assignment method.

Related