Muhammad Mansha
Muhammad Mansha

Reputation: 1007

Best approach to Insert Data in Mysql through Laravel

Below are the two ways to insert data in MySql through laravel Way 1:

$post = Post::create([
'title' => $request->input('title'),
'body' => $request->input('body')
]);

Way 2:

$post = new Post;
$post->title = $request->input('title');
$post->body = $request->input('body');
$post->save();

I just want to know which approach is better and why? Could anyone please tell which approach is better?

Upvotes: 0

Views: 175

Answers (1)

Ismoil  Shifoev
Ismoil Shifoev

Reputation: 6001

Model::create is a simple wrapper around this, if you look at its implementation:

public static function create(array $attributes = [])
{
    $model = new static($attributes);

    $model->save();

    return $model;
}

save()

save() method is used both for saving new model, and updating existing one. here you are creating new model or find existing one, setting its properties one by one and finally saves in database

save() accepts a full Eloquent model instance

$comment = new App\Comment(['message' => 'A new comment.']);

$post = App\Post::find(1);`

$post->comments()->save($comment);

create()

while in create method you are passing array, setting properties in model and persists in database in one shot.

create() accepts a plain PHP array

$post = App\Post::find(1);

$comment = $post->comments()->create([
    'message' => 'A new comment.',
]);

Upvotes: 3

Related Questions