schutte
schutte

Reputation: 2166

How to return model with relationsip in laravel?

I have two model Product and Category.

The categories table have id, and name columns.

While the products table have id, name, and category_id [foreign_key to category].


Here is my below code (already have category with values of 1, "School Supply"):

$product = new Product;
$product->category_id = 1;
$product->name = "pencil";
$product->save();

return $product->with('category');

My question is why it returns an error below when I try to get the data with the relation model? Someone knows how to do it exactly?

[34;4mIlluminate\Database\Eloquent\Builder[39;24m {#4069}

Upvotes: 0

Views: 51

Answers (1)

Aashish gaba
Aashish gaba

Reputation: 1776

You can lazy eager load the relations using load method instead of with.

with is used for eager loading.

$product->load('category');
return $product;

Upvotes: 1

Related Questions