Ave
Ave

Reputation: 4430

How to get name of a field with relationship on Laravel 5?

How do I see the name of a related field instead of ID?

I have a Product table and Category_Product table. In table Product, I have a fields cateproduct_id (number type) I want to get it into my front end. But it shows a number.

Have any method to convert cateproduct_id to a name of category product?

Example: get name of category is Nokia instead of cateproduct_id = 4.

Here is the controller Product like:

public function index() {
    $products = Product::with('cateproductId')->get();
    return view('duan/list', compact('products'));
}

The model of Product:

class Product extends Model
{
    public function cateproductId(){
        return $this->belongsTo(Category_Product::class);
    }
}

In the admin, I get list category and choose a category for my product.

In the frontend page, I need get name category of Product instead of get id category of Product:

<div class="list">
    @foreach($products as $item) 
        <h1>{{$item->cateproductId->name}}</h1>
    @endforeach
</div>

I tried to debug like:

<div class="list">
    @foreach($products as $item) 
        {{dd($item)}}
    @endforeach
</div>

result like:

#relations: array:1 [▼
    "cateproductId" => null
  ]

Upvotes: 0

Views: 1808

Answers (1)

Yusuf Eka Sayogana
Yusuf Eka Sayogana

Reputation: 401

add the foreign key in second parameter

class Product extends Model
{
    public function cateproductId(){
        return $this->belongsTo(Category_Product::class,'cateproduct_id');
    }
}

Upvotes: 2

Related Questions