0

I have two tables in Laravel Eloquent:

UserCategory:
id | user | category

and

Category:
id | name 

UserCategories relates to Category trough belongsTo:

class UserCategory extends Model
{
   public function category()
   {
       return $this->belongsTo('App\Category', 'category');
   }
}

But when I try to get UserCategories with Categories I got integer value (instead of Category model)

$categories = [];
$userCategory = UserCategory::where('user', $user->id)->with('category')->get();

foreach($userCategory as $item) {
   $categories[] = $item->category->name;
}   

When I try to get the category's name I see the second error:

Trying to get property 'name' of non-object

Curious thing, that when I use dd($item) I see that $item has correct relation to Category object, but dd($item->category) returns integer value (category id) instead of category model.

2 Answers 2

5

You have conflicting names. You have both a category column, and a category relationship. By saying $item->category its showing you the category column value. Try changing the relationship name to something else and see if that works.

The best practice would be to use a column name of category_id, but if changing the column name isn't feasible in your situation then the relationship name will work just as well.

2
  • 2
    You can also use $item->getRelation('category')->name if it's not possible to rename the column or the relationship. Nov 18, 2019 at 16:01
  • Thank you! Good advice!
    – FFFFFF
    Nov 18, 2019 at 17:38
1

Change your relation name or id name here because here your relation name & column name is same

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.