Vishal Desai
Vishal Desai

Reputation: 189

laravel 5 where() not working

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

Upvotes: 1

Views: 58

Answers (1)

futureweb
futureweb

Reputation: 442

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.

Upvotes: 1

Related Questions