Search code examples
phpeloquentlaravel-5.3one-to-many

Save multiple record in one to many relation laravel 5


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?


Solution

  • 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])    
    ]);