Search code examples
phplaravelurlmethodstransmission

Transmission variable of URL to the method in Laravel


) I have method:

public function show($id){
$categories = Category::findOrFail($id);
$productsList = Category::with(['products' => function ($query) {
                  $query->where(['category_id', 19]);
              }])->get();
return view('categories.showcategory', compact('categories', 'productsList'));
}

This method returned a list of products in the selected category. Number 19 is selected ID category. The URL to list of products in the selected category looks like this: www.[...]magazyn_michal/public/addcategory/19 The question is: How can I pass a dynamic value numeric ID category (19) of the URL to the method ?? I try this (but not work):

public function show($id){
$categories = Category::findOrFail($id);
$productsList = Category::with(['products' => function ($query) {
                  $query->where(['category_id' => $categories->id]);
              }])->get();
return view('categories.showcategory', compact('categories', 'productsList'));
}

Laravel returned:

Undefined variable: categories

This way also does not work:

public function show($id){
$categories = Category::findOrFail($id);
$productsList = Category::with(['products' => function ($query) {
                  $query->where('category_id', Input::get('category_id'));
              }])->get();
return view('categories.showcategory', compact('categories', 'productsList'));
}

Laravel nothing does not return. Empty list of products in the selected category.

routes.php file:

Route::get('/', 'ProductsController@index');
Route::get('/contact', 'PagesController@contact');
Route::resource('/addarticle', 'ArticlesController');
Route::resource('/addcategory', 'CategoriesController');
Route::resource('/listcategory', 'CategoriesController@listCategory');
Route::resource('/warehouse', 'ProductsController');
Route::auth();
Route::get('/home', 'HomeController@index');

model category.php:

public function products(){
    return $this->hasMany('App\Product');
}

model product.php:

public function category(){
    return $this->belongsTo('App\Category');
}

I using this: https://laravel.com/docs/5.2/eloquent-relationships#constraining-eager-loads


Solution

  • OK I repair this problem. Now it's working ;)

    public function show($id){
    $categories = Category::findOrFail($id);
    $categoryID = Input::get('category_id');
    $productsList = Category::with(['products' => function ($query) use($id) {
                      $query->where('category_id', '='  ,$id);
                  }])->get();
    return view('categories.showcategory', compact('categories', 'productsList'));
    }