Save multiple record in one to many relation laravel 5

15,049

Ok, let's begin with an example from https://laravel.com/docs/5.4/eloquent-relationships:

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

$post->comments()->saveMany([
    new App\Comment(['message' => 'A new comment.']),
    new App\Comment(['message' => 'Another comment.']),
]);

Problem

You pass an array with arrays. That's wrong.

Solution

You need to pass an array with Size objects, simplified like so:

$product_id->Size()->saveMany([
    new App\Size(['size' => 1])    
]);
Share:
15,049
Mutasim Fuad
Author by

Mutasim Fuad

Updated on August 06, 2022

Comments

  • Mutasim Fuad
    Mutasim Fuad over 1 year

    I'm trying to save multiple records in a one to many relationship. I have two models as following.

    Product Model

    class Product extends Model
    {
        protected $primaryKey = 'product_id';
        public $timestamps = FALSE;
    
        public function Size(){
            return $this->hasMany('App\Size');
        }
    
    }
    

    Size Model

    class Size extends Model
    {
        public $timestamps = FALSE;
        protected $fillable = ['product_id','size'];
    
        public function Product(){
            return $this->belongsTo('App\Product');
        }
    }
    

    I want to save the sizes of the product. My controller is

    public function store(Request $request){
    
            $product_id = Products::select('product_id')->orderBy('product_id','desc')->first();
    
            if($request->size_m) $sizes[] = array("size" => $request->size_m );
            if($request->size_l) $sizes[] = array("size" => $request->size_l);
            if($request->size_s) $sizes[] = array("size" => $request->size_s);
    
            $product_id->Size()->saveMany($sizes);
    
    
        }
    

    But I'm getting the following error

    FatalThrowableError in HasOneOrMany.php line 221: Type error: Argument 1 passed to Illuminate\Database\Eloquent\Relations\HasOneOrMany::save() must be an instance of Illuminate\Database\Eloquent\Model, array given, called in D:\e-commerec\blog\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Relations\HasOneOrMany.php on line 237

    What is the problem?

  • Mutasim Fuad
    Mutasim Fuad about 7 years
    Thanks. That helped
  • Mutasim Fuad
    Mutasim Fuad about 7 years
    I am also having a problem with updating the relations consider this models and i have to update it. Unlike many to many relation's sync() methode is threre any way to update one to many relations or may be another way to do it. Can yo help me? There is a methode call associate(). But i didn't understood how it works from the documentation
  • schellingerht
    schellingerht about 7 years
    Do you mean that you only want to save unique relationships?
  • Mutasim Fuad
    Mutasim Fuad about 7 years
    stackoverflow.com/questions/43109293/… here is the question link.
  • schellingerht
    schellingerht about 7 years
    Ok, see my answer ;-)