<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Catalog extends Model
{
protected $fillable = [
'name', 'title', 'uri', 'visible', 'parent_id', 'image_path'
];
public $timestamps = false;
public function subCatalogs(){
return $this->hasMany('App\Catalog', 'parent_id');
}
public function parent(){
return $this->belongsTo('App\Catalog', 'parent_id');
}
public function brands(){
return $this->belongsToMany('App\Brand');
}
public function sections(){
return $this->belongsToMany('App\Section');
}
public function countProduct(){
//
}
}
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Traits\ProductsCount;
class Brand extends Model
{
use ProductsCount;
public $timestamps = false;
public function catalog()
{
return $this->belongsToMany('App\Catalog');
}
}
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Traits\ProductsCount;
class Section extends Model
{
use ProductsCount;
public $timestamps = false;
public function catalog()
{
return $this->belongsToMany('App\Catalog');
}
}
<?php
namespace App\Traits;
trait ProductsCount
{
public function products(){
return $this->belongsTo('App\Product');
}
}
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model {
public function __construct($product_table){
parent::__construct();
$this->table = $product_table;
}
public function brand(){
return $this->belongsTo('App\Brand');
}
public function section(){
return $this->belongsTo('App\Section');
}
}
<?php
namespace App\Http\Controllers;
use App\Catalog;
use App\Brand;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
class CatalogController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('web');
}
public function showCatalog(Request $request){
$uri = trim($request->getPathInfo(),"/");
$catalog = Cache::rememberForever('catalog.' . $uri, function () use ($uri){
$catalog = Catalog::with(['subCatalogs.brands','parent.parent','brands', 'sections','subCatalogs' => function ($query) {
$query->where('visible', 1);
}])->where('uri', $uri)
->where('visible', 1)
->first();
if ($catalog === null) abort(404);
return $catalog->toArray();
});
$catalog = Catalog::with(['subCatalogs.brands','parent.parent','brands', 'sections','subCatalogs' => function ($query) {
$query->where('visible', 1);
}])->where('uri', $uri)
->where('visible', 1)
->first();
dd($catalog->brands()->withCount('products')->get());
$data['catalog'] = $catalog;
return view('pages.catalogs', $data);
}
}