i'm new laravel, using orm trying retrieve data parentcategory table using foreign key present in category table.
following code in category model:
<?php namespace app; use illuminate\database\eloquent\model; class category extends model { protected $table='category'; public function parentcategory(){ return $this->belongsto('app\parentcategory','mcategoryid'); } }
following parentcategory model code:
<?php namespace app; use illuminate\database\eloquent\model; class parentcategory extends model { protected $table='maincategory'; public function categories(){ return $this->hasmany('app\category'); } }
following code of categorycontroller using retrieve data:
class categorycontroller extends controller { function index(){ $category=category::all()->with('parentcategory'); $parentcategory=parentcategory::all(); return view('admin.category',['categories'=>$category,'parentcategories'=>$parentcategory]); } function add(request $request){ $category= new category(); $category->categoryname=$request["name"]; $category->mcategoryid=$request["parentcategory"]; $category->save(); return redirect()->route('category'); } }
the error further states: at collection->__call('with', array('parentcategory')) in categorycontroller.php line 17
in index()
function, can try
$category = category::with('parentcategory')->get();
this should solve problem. follow eager loading documentation.
Comments
Post a Comment