我试图得到所有的主要类别在标题的网站,但只有一个类别显示,谁能提供这个解决方案?
以下是ProductsController:
ProductsController.php
public function products($url = null)
{
$categories = Category::with('products')->where(['parent_id'=>0])->get();
$categoryDetails = Category::where(['url' => $url])->first();
if($categoryDetails->parent_id==0)
{
//if url is main category url
$subCategories = Category::where(['parent_id'=>$categoryDetails])->get();
$cat_ids = "";
foreach ($subCategories as $subCat) {
$cat_ids .= $subCat->id.",";
}
$productsAll = Product::whereIn('category_id',array($cat_ids))->get();
}
else
{
//if url is sub category url
$productsAll = Product::where(['category_id' => $categoryDetails->id])
->get();
}
return view('products.listing')
->with(compact('categories','categoryDetails','productsAll'));
}在listing.blade.php上,我写了这篇文章,将它与类别联系起来:
{{ $categoryDetails->name }}主计长守则:
Controller.php
<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use App\Category;
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
public static function mainCategories(){
$mainCategories = Category::where(['parent_id' => 0])->get();
$mainCategories = json_decode(json_encode($mainCategories));
/*echo "<pre>"; print_r($mainCategories); die;*/
return $mainCategories;
}
}我在header视图中编写的代码:
header.blade.php
<?php use App\Http\Controllers\Controller;
$mainCategories = Controller::mainCategories();
?>
<!--some html-->
@foreach($mainCategories as $cat)
<div class="dropdown-content">
<a href="{{ asset('products/'.$cat->url) }}" style="margin-bottom: -10px;">{{ $cat->name }}</a>
</div>
@endforeach发布于 2019-01-15 16:30:29
试着改变
<?php use App\Http\Controllers\Controller;
$mainCategories = Controller::mainCategories();
?>至
<?php
use App\Controller;
$mainCategories = Controller::mainCategories();
?>或更直接地:
<?php
$mainCategories = App\Controller::mainCategories();
?>在header.blade.php中
发布于 2019-01-15 18:03:20
您可以为此使用视图数据(https://laravel.com/docs/master/views#passing-data-to-views):
在您的App/Providers/AppServiceProvider.php文件中:
public function boot()
{
View::share('mainCategories', Category::where(['parent_id' => 0])->get());
}只需使用:
@foreach($mainCategories as $cat)
// .... your code
@endforeach在模板文件中。
https://stackoverflow.com/questions/54202818
复制相似问题