Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

adeel's avatar

Fetching category name using foreign key (category_id) in blade

Hi there, i am fetching data form products table. i can fetch category_id (from products table) successfully by this code but i want to get its Category name from category table.

            @foreach($products as $product)
                <tr class="odd">
                    <td class=" sorting_1"> {{ $product->title }} </td>
                    <td class=" "> {{ $product->category_id }} </td>
                    <td class=" ">{{ $product->price }}</td>
                    <td class=" "> {{ $product->availability }} </td>
                    <td class=" "><a href="#">Edit</a> / <a href="">Delete</a></td>
                </tr>
             @endforeach
0 likes
10 replies
phildawson's avatar
class Product extends Model
{
    public function category()
    {
        return $this->belongsTo(Category::class);
    }
}
$product->category->name;
adeel's avatar

@phildawsome

Thanks for your reply. Now i am getting this error

FatalErrorException in Model.php line 827: Class 'category' not found

Francismori7's avatar
Level 52

@adeel Import the Category class. Make sure your Category is a model too that links to the category_ids and stuff.

You may also want to retrieve products while eager loading the categories:

$products = Product::all()->load('category');

or

$products = Product::with('category')->get();
1 like
phildawson's avatar

@adeel No need to import if in the same namespace but I was assuming you have a file called Category.php in the app folder with at least

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    //
}
adeel's avatar

oh .. i was using this in model.

public function category() { return $this->belongsTo('category'); }

Your first solution worked. Thank You sooo much @phildawson :)

phildawson's avatar

@adeel :) Ah yeah you need the ::class to resolve back to the string 'App\Category'

The tip from @Francismori7 is worth following to save on db query for each loop. I'd go with the latter 'with' unless there is a condition.

Please or to participate in this conversation.