[enter image description here][1]
I'm trying to store multiple images in the database. I have products table and images tables. I have faced the issue for image not showing the product list page. I am trying to more tutorials codes unfortunately my issues not solve. Please check the below cods and help me the problem solve.
Products Model
class Products extends Model
{
use HasFactory;
protected $table = 'cw_products';
protected $fillable =
['product_id','product_title','product_details','product_cid'];
public function images()
{
return $this->hasMany(ProductsImage::class, 'images_pdct_id', 'images_id');
}
}
ProductsImage Model
class ProductsImage extends Model
{
use HasFactory;
protected $table = 'cw_products_images';
protected $fillable =
['images_id','images_pdct_id','images_image','images_thumbnail'];
public function products()
{
return $this->belongsTo(Products::class, 'product_id');
}
}
ProductsController
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use App\Models\Products;
use App\Models\ProductsImage;
use Hash;
use Session;
use File;
use Image;
class ProductsController extends Controller
{
public function index(Request $request)
{
$data = array();
//$products = Products::where('product_status', '>=', 0)->orderBy('product_id', 'desc')->paginate(30); // Replace 100
$products = Products::with('images')->where('product_status', '>=', 0)->orderBy('product_id', 'desc')->paginate(30);
//DD($products);
return view('webadmin.pages.products',compact('data','products'));
}
}
Products List View Page
@if($products->count())
@foreach($products as $product)
<tr style="color:rgb(26, 25, 25);">
<td>
@foreach($product->images as $pimages)
<!--$pdctImage = $product->images[0]->images_thumbnail;
dd($pdctImage); -->
<img src="../../assets/img/products/thumbnail/{{ $pimages->images_thumbnail }}" alt="ProjectImage" style="width: 50%; height: 50px;"/>
@endforeach
</td>
<td>{{ $product->product_title }}</td>
</tr>
@endforeach
@endif
CodePudding user response:
The relation ships are defined using foreign key and local key like this - return $this->hasMany(Comment::class, 'foreign_key', 'local_key'); -https://laravel.com/docs/9.x/eloquent-relationships . So you would need to change relationship in both models.
class Products extends Model
{
use HasFactory;
protected $table = 'cw_products';
protected $fillable =
['product_id','product_title','product_details','product_cid'];
public function images()
{
return $this->hasMany(ProductsImage::class, 'images_pdct_id', 'product_id');
}
}
class ProductsImage extends Model
{
use HasFactory;
protected $table = 'cw_products_images';
protected $fillable =
['images_id','images_pdct_id','images_image','images_thumbnail'];
public function products()
{
return $this->belongsTo(Products::class, 'product_id','images_pdct_id');
}
}