I’m making a project where I use the foreign key from a shop in products. The foreign key works but when I want to show it in my blade by using $product->shop_id->shop_name
, it gives a blank spot. My foreign key is named ‘shop_id’.Product page without shop name
This is my code:
ProductController:
public function getProduct() { $products = DB::table('products')->inRandomOrder()->simplePaginate(15); return view('product', ['products' => $products]); }
product.blade.php
@foreach($products as $product) <div class="column4 "> <div class="box ProductPage"> <img src="{{$product->product_image}}" alt="" class="image image-full"/> <h3>{{$product->product_name}}</h3> <p>Inhoud: {{$product->product_volume}}</p> <p><u>€{{$product->product_price}}</u></p> <p>Winkel:{{$product->shop_id->shop_name}}</p> </div> <a href="{{$product->product_url}}" class="button button-small">Bekijk product</a> </div>
Product Model
<?php namespace AppModels; use IlluminateDatabaseEloquentFactoriesHasFactory; use IlluminateDatabaseEloquentModel; class Product extends Model { use HasFactory; /** * @var string * * */ protected $table = 'products'; /** * @var array * * */ protected $fillable = [ 'product_name', 'product_volume', 'product_price', 'product_url', 'product_image', ]; /** * @return IlluminateDatabaseEloquentRelationsHasOne * * */ public function shop() { return $this->hasOne('AppShop', 'shop_id'); } }
Shop model
<?php namespace AppModels; use IlluminateDatabaseEloquentFactoriesHasFactory; use IlluminateDatabaseEloquentModel; class Shop extends Model { use HasFactory; /** * @var string * * */ protected $table = 'shops'; /** * @var array * * */ protected $fillable = [ 'shop_name', ]; /** * @return IlluminateDatabaseEloquentRelationsBelongsTo */ public function product() { return $this->belongsTo('AppProduct', 'shop_id')->withDefault(); } }
Advertisement
Answer
Your provided wrong namespace and keys in your relationship declaration. You must change as in example below to be able use these methods
Product.php
public function shop() { return $this->hasOne(Shop::class, 'shop_id', 'shop_id'); }
After that you can access product shop using
<p>Winkel: {{ $product->shop->shop_name }}</p>