//my controller
public function show_card(){
if(Auth::id())
{
$id=Auth::user()->id;
$cards=Card::with('product_card')->where('user_id','=',$id)->get();
return view('home.show_cart',compact('cards'));
}
else{
return redirect('login');
}
}
//product model
public function product_card()
{
return $this->hasMany(Card::class,'product_id','id');
}
//card model
public function product_card()
{
return $this->belongsTo(Product::class);
}
//I want to access product table data using product_id foreign key in card table.`
2
Answers
Your relations are incorrect. The Card model should have the belongsTo relationship to the Product model because a card belongs to a product. On the other hand, a product can have many cards so it should have a hasMany relationship to the Card model.
So do these modifications:
In the Card model:
In your controller:
In the view, you can access product information like this:
In your Product model, you should define the relationship as a hasMany because one product can be associated with many cards:
In your Card model, you should define the relationship as a belongsTo because each card belongs to one product:
With these corrections, you should be able to access product attributes from the cards. Here’s how you would do it in your controller:
Now, when you access
$card->product->attribute
, you should get the attributes of the associated product. Make sure your database schema is correctly set up with the foreign key constraints.