Attempt to read property "name" on null in laravel relations

59 Views Asked by At

i made one-to-many relation in laravel with category and product, but the problem is that the relation is ok to categroy side but on the product side when i fetch data then they say me "Attempt to read property "name" on null" [this is category model]this is product blade]

this is product model

this is product controller i am trying to fetch the product with related category name

1

There are 1 best solutions below

0
Harshad Kanani On

setting up a basic one-to-many relationship between Category and Product models in Laravel

Imagin you have a Category model with the following product relationship

// Category.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    public function products()
    {
        return $this->hasMany(Product::class);
    }
}

And a Product model with the following category relationship

// Product.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;

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

Now, in the controller, when fetching products with their related category name, you can use eager loading

// ProductController.php
namespace App\Http\Controllers;
use App\Models\Product;

class ProductController extends Controller
{
    public function index()
    {
        $products = Product::with('category')->get();
        return view('products.index', compact('products'));
    }
}

In your blade view 'products/index.blade.php' , you can loop through the products and access the related category name

@foreach($products as $product)
    <p>{{ $product->name }} - {{ $product->category->name }}</p>
@endforeach

Make sure your database tables are set up with the foreign key constraints correctly. The products table should have a category_id column that references the id column in the categories table