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

前端 未结 2 1028
余生分开走
余生分开走 2020-12-13 09:38

I need to know what is the difference of save() and create() function in laravel 5. Where we can use save() and create()

相关标签:
2条回答
  • 2020-12-13 10:13

    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 creating method you are passing an array, setting properties in model and persists in the 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 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',
            ];
    }
    
    0 讨论(0)
  • 2020-12-13 10:18

    If you are looking for short answer it is on laravel doc as

    The Create Method

    In addition to the save and saveMany methods, you may also use the create method, which accepts an array of attributes, creates a model, and inserts it into the database.

    Again, the difference between save and create is that

    save accepts a full Eloquent model instance

    while create accepts a plain PHP array:

    $post = App\Post::find(1);
    
    $comment = $post->comments()->create([
        'message' => 'A new comment.',
    ]);
    

    if you are looking for details see @Tony Vincent's answer.

    0 讨论(0)
提交回复
热议问题