PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, November 15, 2022

[FIXED] How to return model with relationsip in laravel?

 November 15, 2022     eloquent, laravel, laravel-6, php     No comments   

Issue

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}


Solution

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

with is used for eager loading.

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


Answered By - Aashish gaba
Answer Checked By - Mildred Charles (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing