我正在使用的视图首先显示所有产品,在侧边栏上,用户可以看到类别列表。我的目标是当用户按任何类别时,它将仅显示该类别的产品。但是,由于有2个控制器正在与此视图交互并发送相同的数据,因此一个未运行(CategoriesController)。它没有显示任何错误,只是当我点击每个类别的链接时,它不会重新加载页面。 这是我的ProductsController:
class ProductsController extends Controller
{
// display all products and categories
public function index() {
$products = Product::all();
$categories = Category::all();
return view('frontend.product', compact('products','categories'));
}
我的CategoriesController:
class CategoriesController extends Controller
{
public function showProducts($category_id) {
$products = Category::find($category_id)->products;
return view('frontend.product', compact('products'));
}
以下是我的观点:
// Products part
@foreach($products as $product)
{{ $product->name }}
@endforeach
//Categories part
@foreach($categories as $category)
<a href="{{ route('categories', [$category->id]) }}">{{ $category->name }} </a>
@endforeach
路线:
Route::get('/products', [ 'as' => 'products', 'uses' => 'frontend\ProductsController@index']);
Route::get('/categories/{category_id}', ['as' => 'categories', 'uses' => 'backend\CategoriesController@showProducts']);
答案 0 :(得分:1)
只需在showProducts
函数中包含所有类别,并省略当前类别:
public function showProducts($category_id)
{
$categories = Category::whereNotIn('id', $category_id)->get();
$products = Category::find($category_id)->products;
return view('frontend.product', compact('products', 'categories'));
}
现在使用的变量之间不会有任何差异。
答案 1 :(得分:0)
如果我没有误解,我认为你可以在刀片中使用@inject。例如:
namespace App\Presenters;
use App\User;
class UserPresenter
{
/**
* 是否顯示email
* @param User $user
* @return string
*/
public function showEmail(User $user)
{
if ($user->show_email == 'Y')
return '<h2>' . $user->email . '</h2>';
else
return '';
}
}
和
<div>
@inject('userPresenter', 'MyBlog\Presenters\UserPresenter')
@foreach($users as $user)
<div>
{!! $userPresenter->showEmail($user) !!}
</div>
</div>