1

i have two tables, categories and subcategories, and each item in subcategories belongs to categories by foreign key "category_id".

i have two models one for categories and one for subcategories, and one controller.

my category model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    //
    public function subcategories()
    {
        return $this->hasMany('\App\Subcategory');
    }

}

subcategory model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Subcategory extends Model
{
    protected $fillable = [

        'sub_category_name',
        'category_id'
    ];
}

and CategoriesController

<?php

namespace App\Http\Controllers;

use App\Category;
use App\Subcategory;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class CategoriesController extends Controller
{
    //return array of categories
    public function categories ()
    {

        $categories =  Category::where('category_name', '=', 'Construction Machines')->subcategories;
        return $categories;
    }
}

question is when i do Category::find()->subcategories i get the expected results. but when i use where(), it gives me Undefined property: Illuminate\Database\Eloquent\Builder::$subcategories error

9
  • 1
    $categories = Category::with('subcategories')->where('category_name', '=', 'Construction Machines')->get(); return $categories; Commented Oct 29, 2015 at 19:36
  • also how can i access this variable in view without return make()? because the page i need this data on already is loaded, i need to populate drop down list with it? Commented Oct 29, 2015 at 19:41
  • @VishalDesai is it solved with futureweb comment or still? Commented Oct 29, 2015 at 19:58
  • yes, but I'm trying to access that return $categories inside my view. Commented Oct 29, 2015 at 20:00
  • 1
    @futureweb if you leave answer I will vote it up. Commented Oct 29, 2015 at 20:25

1 Answer 1

1

As requested, you will need to return a view with the categories variable

 return view('view.name',compact('categories'); 

then

  {{dd($categories)}} 

or

 <? print_r($categories); ?>

in your view and it will output the data. You can access a specific value by

 @foreach($categories as $category) 
    {{$category->name}} 
 @endforeach 

assuming you are using blade and you have a name value in your categories collection.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.