Divine SCONTY
Divine SCONTY

Reputation: 31

Failure to read field data using foriegn key from different table

Please I am trying to access the field name in my categories table using the foreign key category in my products table but I keep getting Attempt to read property "name" on int error

these are my relationships in Product.php and Categories.php respectively

//product
    namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Models\Categories;

class Product extends Model
{
    use HasFactory;

    protected $casts = [
        'tags' => 'array',
        'colors' => 'array',
        'other_images' => 'array'
    ];

    protected $guarded = ['id'];
    

    public function category(){
        return $this->belongsTo(Categories::class, "category");
    }



 //categories
    
    namespace App\Models;
    
    use Illuminate\Database\Eloquent\Factories\HasFactory;
    use Illuminate\Database\Eloquent\Model;
    use App\Models\Product;
    
    class Categories extends Model
    {
        use HasFactory;
    
        protected $guarded = ['id'];
    
        public function products(){
            return $this->hasMany(Product::class, "category");
    }
    
    }

and this is my blade template

@if ($product->count())
            @foreach ($product as $index => $product)
            <button type = "button" class = "btn m-2 text-dark" data-filter = ".{{$product->category}}">{{$product->category->name}}</button>
            @endforeach
        @endif

the category field is a foreign key with the reference id in categories table

Upvotes: 0

Views: 29

Answers (1)

Mohamed Surour
Mohamed Surour

Reputation: 165

I assume that you have in your products table column with name category_id, if that's the case then you should remove "category" from

 public function category(){
    return $this->belongsTo(Categories::class, "category");
}

to be

 public function category(){
    return $this->belongsTo(Categories::class);
}

in your Product model

Please refer to this part in the documentation here

Also, change the relationship in

public function products(){
        return $this->hasMany(Product::class, "category");
}

to be

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

Upvotes: 1

Related Questions