Reputation: 6990
I am trying to create a relationship between Category and Product but somehow I couldn't use the category to connect into the product table and prints out the product names and instead I get the category's name
Table Name: products
Columns: id, name, price, category_id, description
Table Name: categories
Columns: id, name, description
id: 1
name: product1
price: 10
category_id: 1
description: p1
---------------
id: 2
name: product2
price: 10
category_id: 1
description: p2
id: 1
name: category1
description: c1
---------------
id: 2
name: category2
description: c2
class Product extends Eloquent
{
protected $product = 'products';
public function category()
{
return $this->belongsTo('Category');
}
}
class Category extends Eloquent
{
protected $category = 'categories';
public function product()
{
return $this->hasMany('Product', 'category_id');
}
}
class ProfileController extends BaseController
{
public function user($username)
{
$user = User::where('username', '=', $username);
if ($user->count())
{
$user = $user->first();
$title = 'User Profile';
$category = Category::find(1);
$products = Category::find(1)->name;
return View::make('profile.user', compact('user', 'title', 'category', 'products'));
}
return 'User Not Found. Please Create an Account';
}
}
@extends('layouts.master')
@section('content')
{{ Auth::user()->username }}
<br>
{{ Auth::user()->email }}
<br>
<h1>{{ 'Category name: '. $category->name }}</h1>
<br>
<h3>{{ 'Category Description: ', $category->description }}</h3>
<br>
{{ $products }}
@stop
at first where the {{$products}}
I used a foreach loop
@foreach($products as $product)
{{$product}}
@endforeach
but then I got this error
ErrorException
Invalid argument supplied for foreach() (View: J:\wamp\www\test\app\views\profile\user.blade.php)
so I tried var_dump($products)
and realized $products
gives out category1
which is the name of the category but what I want is printing the name of all the products which has category_id 1
Can someone give me a hand with this? Did I mess something up with the relationship or I did something stupid with the codes?
Upvotes: 1
Views: 986
Reputation: 565
In your controller:
$category = Category::find(1);
$products = $category->product;
Then in your template you can use:
@foreach ($products as $product)
{{ $product->name }}
@endforeach
Better yet you could use eager loading and forget about assigning products manually:
Controller:
$category = Category::with('product')->where('id', 1)->first();
Template:
@foreach ($category->product as $product)
{{ $product->name }}
@endforeach
PS: Read more on eager loading here: http://laravel.com/docs/eloquent#eager-loading in order to prevent the dreaded N + 1 query problem!
Upvotes: 3