Reputation: 391
I have two tables
product: id|category ...
category: id|name ...
product.category is a foreign key linked to category.id . I am building a basic CRUD and I would like to display all Products in the the product table as well as the name of the category they belong to rather than their category ID. TO do this, while searching the laravel documentation I came across the query builder and I achieved my goal.
public function index()
{
$products = \DB::table('products')
->join('categories', 'products.category', '=', 'categories.id')
->select('*')
->get();
return view('product' ,compact('products'));
}
Under my models for product and category I have created the appropriate relationships.
product.php :
public function category()
{
return $this->belongsTo('App\Category');
}
category.php :
public function products()
{
return $this->hasMany('App\Product');
}
I keep hearing about the power of Eloquent and was wondering how I could achieve a similar result with eloquent and if eloquent is designed for such operations or if the query builder is the right way to go. Every tutorial online seems to only use the post and comments scenario of getting all comments belonging to a post.
Upvotes: 0
Views: 649
Reputation: 8618
You can use this code
public function index()
{
$products = Product::with('category')->get();
return view('product' ,compact('products'));
}
In blade
@foreach($products as $product)
{{$product->name}}
{{$product->category->name ?? ''}}
//or
@if ($product->category)
$product->category->name
@endif
@endforeach
Also if in project table foreign key is not equal category_id
. In your case
public function category()
{
return $this->belongsTo('App\Category', 'category');
}
Upvotes: 1