I'm new to laravel. I want to access the products
belongs to the category
. There is One-to-Many relation between them. To get this data I created a function inside ProductsController
named getCtgProducts()
to do just that.
I know it a bad practice to query a database straight from views, hence I am writing the database query in the controller and trying to access it inside the blade.
Can someone tell me what I'm doing wrong?
What is the proper way to access the controller function inside the blade view? I'm using Laravel Framework v9.7.0
@foreach ($ctgs as $ctg)
<h1> $ctg->name </h1> // -- It is working. Showing the correct ctgs names
<div class=container>
@if (isset($products))
@foreach ({{ App\Http\Controllers\ProductsController::getCtgProducts($ctg->id) }} as $product)
<h1> $product->name </h1>
@endforeach
@endif
</div>
@endforeach
ProductsController
class
<?php
namespace App\Http\Controllers;
use App\Models\Ctg;
use App\Models\Product;
class ProductsController extends Controller
{
public function index(Request $request)
{
$products = Product::all();
$ctgs = Ctg::all();
return view('ui\welcome', compact('products', 'ctgs'));
}
public static function getCtgProducts(){
$ctgProducts = DB::table('products')->where('ctg_id', $ctgId);
return $ctgProducts;
}
}
CodePudding user response:
Calling controller from blade is bad practice move your getCtgProducts() method logic to Category Model:
public function getCtgProducts(){
$ctgProducts = DB::table('products')
->where('ctg_id', $this->id)->get();
return $ctgProducts;
}
Blade file:
@foreach ($ctgs as $ctg)
<h1> $ctg->name </h1> // -- It is working. Showing the correct ctgs names
<div class=container>
@foreach ($ctg->getCtgProducts() as $product)
<h1> $product->name </h1>
@endforeach
</div>
@endforeach
Better way: Since there's one-to-many relationship in Category Model you should have a relationship method:
public function products() {
return $this->hasMany(Product::class);
}
Blade:
@foreach ($ctgs as $ctg)
<h1> $ctg->name </h1> // -- It
is working. Showing the correct ctgs
names
<div class=container>
@foreach ($ctg->products as
$product)
<h1> $product->name </h1>
@endforeach
</div>
@endforeach