jagarkin
Posted on May 9, 2021
hello i am using laravel 8, i have a product and image table and i want to be able to upload 3 images with each product
product model*
class Product extends Model implements Auditable
{
use HasFactory, AuditableTrait;
const FILLABLE = ['name','price','description'];
protected $fillable = ['name','price','description'];
public function images()
{
return $this->hasMany(Image::class, 'id');
}
}
product migration
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateProductsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->double('price');
$table->text('description');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('products');
}
}
image model
class Image extends Model
{
use HasFactory;
protected $fillable = ['product_id', 'file_path'];
}
image migration
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateImagesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('images', function (Blueprint $table) {
$table->id();
$table->foreignId('product_id')->constrained();
$table->string('file_path');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('images');
}
}
and this the methode inside my product controller that supposed to store data
public function store(Request $request)
{
$product = Product::create($request->only('name','price','description'));
if($images = $request->file('images')){
foreach($images as $image){
$image->store('product','public');
Image::create([
'product_id' => $product->id,
'file_path' => $image->hashName()
]);
}
}
return $product;
}
when i test this method with postman i was able to store data into product
but the image table stays empty it did not receive any data
any help please!
💖 💪 🙅 🚩
jagarkin
Posted on May 9, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.