What is different between save(), create() function in laravel 5

我只是一个虾纸丫 提交于 2019-11-30 02:00:22
Tony Vincent

Model::create is a simple wrapper around $model = new MyModel(); $model->save() See the implementation

/**
 * Save a new model and return the instance.
 *
 * @param  array  $attributes
 * @return static
 */
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.',
    ]);
    

    EDIT
    As @PawelMysior pointed out, before using the create method, be sure to to mark columns whose values are safe to set via mass-assignment (such as name, birth_date, and so on.), we need to update our Eloquent models by providing a new property called $fillable. This is simply an array containing the names of the attributes that are safe to set via mass assignment:

example :-

class Country extends Model {

    protected $fillable = [
        'name',
        'area',
        'language',
        ];
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!