I would suggest the child data be uploaded at the correct time so the FK's match correctly. Or have a temp field with a name you can later match up to a FK. Name or other identifier. Otherwise it's going to be extremely hard to match these things up.
Create Child Before Parent in laravel 10
i am building e-commerce website, i am using laravel to making api, i have Product Controller , it has fileds: title, description and images, and i make controller for images , so every product has its own images, and i made relationship :
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
use HasFactory;
protected $fillable = ['title', 'description', 'About', 'price', 'discount'];
public function Images()
{
return $this->hasMany(ProductImage::class);
}
}
and the product images:
class ProductImage extends Model
{
use HasFactory;
public function Product()
{
return $this->belongsTo(Product::class);
}
}
in the product images table i have forign key (product_id),now the problem is: in the front end i upload the images before the parent created, which means i upload the images before product created, so the images product_id filed be null, now how to make relationship if i upload child(images) before parent (product) ? or how can i get product_id and put it in exact images thats belong to exact product?
what I do is create a draft product and add images to that. Later, the draft product is saved without being draft.
Very occasionally a draft product might be left behind, but a monthly job can clear them out
I create the draft product in the create controller method, then pass it to the edit function.
public function create()
{
$product = Product::create([
// you might need to put in some dummy values here to get around non-null fields
'status' => 'draft'
]);
return $this->edit($product);
}
public function edit(Product $product)
{
// prep data for edit view etc
}
another advantage is that you only need one form and form request since everything is done through edit.
Please or to participate in this conversation.