Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

laravel 5.5 best way to create data

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?

like image 375
Kenneth Avatar asked Sep 22 '17 00:09

Kenneth


1 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..

like image 134
parker_codes Avatar answered Nov 15 '22 04:11

parker_codes