Noah Hornak
Noah Hornak

Reputation: 131

Create Entity with one to many relationship Laravel

I have a Product class and a Image class. Each product has many Images. I believe I have set up the relationship correctly, but when creating a Product, I'm having trouble creating the Images. I have a function that takes in a request that contains a JSON object containing the Product details, including an array of Images. I convert the JSON into a variable, but if I just save the variable into the database, it just saves the product details, excluding the images. I looked to trid using the following, but the $product variable isn't recognized as a Product type, so therefore, doesn't recognize the images() on the Product class.

$product->images()->save($images)

This is the function used to create the Product:

public function api_create(Request $request)
{
    try {
        $product = new Product;
        $product = json_decode($request->getContent(), true);
        $images = $product['images'];
        return Product::create($product);
    } catch (Exception $exception) {
        return "error";
    }
}

In Product class:

public function images(){
    return $this->hasMany('App\Image', 'productId');
}    

In Image class:

public function product(){
    return $this->belongsTo('App\Product', 'productId');
}

Image db columns: id(PK), productId(FK), imageUrl

Product db columns: id(PK), title, description

Upvotes: 2

Views: 1037

Answers (1)

Alexey Mezenin
Alexey Mezenin

Reputation: 163898

Change this:

$images = $product['images'];
return Product::create($product);

To:

$product = Product::create($product);
foreach ($product['images'] as $image) {
    $product()->images()->create($image);
}
return $product;

This will work if each $image is an array with correct format, something like:

['filename' => 'flower.jpg', 'size' => 54438]

If the format is different, you'll need to map it manually, for example:

->create([
    'filename' => $image['uploaded_file_name'],
    'size' => $image['file_size_in_bytes']
]);

Upvotes: 3

Related Questions