skip to Main Content

//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


  1. 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:

    class Product extends Model {
        public function cards() {
            return $this->hasMany(Card::class, 'product_id', 'id');
        }
    }
    

    In the Card model:

    class Card extends Model {
        public function product() {
            return $this->belongsTo(Product::class, 'product_id', 'id');
        }
    }
    

    In your controller:

    public function show_card(){
        if(Auth::id()) {
            $id=Auth::user()->id;
            $cards=Card::with('product')->where('user_id','=',$id)->get();
            return view('home.show_cart',compact('cards'));
        } else {
            return redirect('login');
        }
    }
    

    In the view, you can access product information like this:

    @foreach($cards as $card)
        {{ $card->product->name }}
    @endforeach
    
    Login or Signup to reply.
  2. In your Product model, you should define the relationship as a hasMany because one product can be associated with many cards:

    public function cards()
    {
        return $this->hasMany(Card::class, 'product_id', 'id');
    }
    

    In your Card model, you should define the relationship as a belongsTo because each card belongs to one product:

    public function product()
    {
        return $this->belongsTo(Product::class, 'product_id', 'id');
    }
    

    With these corrections, you should be able to access product attributes from the cards. Here’s how you would do it in your controller:

    public function show_card()
    {
        if(Auth::id())
        {
            $id = Auth::user()->id;
            $cards = Card::with('product')->where('user_id', $id)->get();
            return view('home.show_cart', compact('cards'));
        }
        else {
            return redirect('login');
        }
    }
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search