2

I know its basic but cant figure it out whats the problem. its seems like i did all things right. I want to make a relation ship with product brands where every product has a brand id which belongs to a Brands also in brands model every brands has many products. i used belongsTo has many relationship to make this but still its showed me error.

Product.php model

namespace App;

use Illuminate\Database\Eloquent\Model;


class Product extends Model
{
     protected $fillable = [
        'sku',
        'name',
        'description',
        'brand_id',
        'image',
        'price',
        'stocks',
        'color',
        'size',
    ];

    protected $table = 'products';

    public function brand() {
        return $this->belongsTo('App\Brand');
    }
}

Brand.php model

namespace App;

use Illuminate\Database\Eloquent\Model;

class Brand extends Model
{
    protected $fillable = [
        'user_id',
        'name',
        'description'
    ];

    protected $table = 'brands';

    public function products() {
        return $this->hasMany('App\Product','brand_id', 'id');
    }
}

routs.php

Route::get('/', function () {
   $products = \App\Product::all();

    echo $products->brand();

});
sagar290
  • 301
  • 3
  • 15

3 Answers3

4

$products is a collection of Product objects, so to get brand for each object you need to iterate over the collection:

foreach ($products as $product) {
    echo $product->brand->name;
}
Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
2

edit

You can use higher order functions to simplify the loop:

$products->each->brand->name
2

You're calling the method via a collection data.

You should loop the products first and you don't need the open close parenthesis when using the relationship.

Instead of

$products = \App\Product::all();

echo $products->brand();

Should be something like this.

$products = \App\Product::all();

foreach($products as $index => $product){
    echo $product->brand; //however this will return the Brand model and you can't echo a Model instead display the data via print_r or put it in $variable. then use the $variable as how you handle a model Data.


 $brand = $product->brand;
    echo $brand->name;
    echo $brand->description;

}

Hope this will enligthen you.

Kenneth Sunday
  • 865
  • 7
  • 14