PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, January 24, 2022

[FIXED] Cannot get data from third table using relation in Laravel

 January 24, 2022     eloquent, laravel, laravel-5     No comments   

Issue

I have three tables, structure are as follows:

products:
id | name | slug | price

product_attributes:
id | attribute_id | value | qty | product_id

attributes :
id | code | name 

Now i'm getting the product and the attributes selected for this particular product using the following relationships but i also want the code and name of the attribute from the third table i.e. attributes:

ProductController.php:

public function show($slug)
{
    $product = $this->productRepository->findProductBySlug($slug);
    return view('site.pages.product', compact('product'));
}

ProductRepository.php

   public function findProductBySlug($slug)
    {
    $product = Product::with('attributes')->where('slug', $slug)->first();

    return $product;
    }

Model : Product.php

public function attributes()
{
    return $this->hasMany(ProductAttribute::class);
}

getting data on view with following code:

{{ dd($product->attributes) }}

but i also want data from the third table i.e. attributes


Solution

Use Many to Many relationship and withPivot to get the pivot attributes:

// Product Model:
public function attributes()
{
    return  $this->belongsToMany(Attribute::class, 'product_attributes')->withPivot('value', 'qty');
}


// Attribute Model:
public function products()
{
    return  $this->belongsToMany(Product::class, 'product_attributes')->withPivot('value', 'qty');
}

So you can get attributes and the pivot's datas:

@foreach($product->attributes as $attr)
    {{$attr->pivot->value}}
    {{$attr->pivot->qty}}
    {{$attr->code}}
    {{$attr->name}}
@endforeach


Answered By - TsaiKoga
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing