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?
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..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With