FFFFFF
FFFFFF

Reputation: 199

Laravel "with" is not populate related model

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.

Upvotes: 0

Views: 345

Answers (2)

albus_severus
albus_severus

Reputation: 3704

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');
   }
}

Upvotes: 1

Brian Thompson
Brian Thompson

Reputation: 14355

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.

Upvotes: 5

Related Questions