Duong Nguyen
Duong Nguyen

Reputation: 159

Laravel 5.3 How to use multiple controllers in one view

I'm working with a view that at first displays all products, and on the sidebar, users can see a list of categories. My aim is when users press on any categories, it will display products of that category only. However, since there are 2 controllers is interacting with this view and send the same data, one is not running(CategoriesController). It does not show any error, just when I click on the link of each of the categories, it does not reload the page. Here is my 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'));
    }

And my CategoriesController:

class CategoriesController extends Controller 
{ 
public function showProducts($category_id) {
        $products = Category::find($category_id)->products;
        return view('frontend.product', compact('products'));
    }

Here is my view:

// 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

And route:

Route::get('/products', [ 'as' => 'products', 'uses' => 'frontend\ProductsController@index']);
Route::get('/categories/{category_id}', ['as' => 'categories', 'uses' => 'backend\CategoriesController@showProducts']);

Upvotes: 1

Views: 1319

Answers (2)

Ohgodwhy
Ohgodwhy

Reputation: 50808

Just include all of the categories in your showProducts function, and omit the current category:

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'));
}

Now there will be no discrepancies between the variables that are being used.

Upvotes: 1

fallen.lu
fallen.lu

Reputation: 77

If I have not misunderstood, I thought you can use @inject in blade. For example:

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 '';
    }
}

and

<div>
    @inject('userPresenter', 'MyBlog\Presenters\UserPresenter')
    @foreach($users as $user)
    <div>
        {!! $userPresenter->showEmail($user) !!}
    </div>
</div>

Upvotes: 0

Related Questions