I have some problems with getting some info from database in Laravel. I'm trying to use where method and specify id that I need to but I always have error like
Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException: The GET method is not supported for this route. Supported methods: POST.
Here is the code Controller
public function select_category($category_id){
$products = Products::where('category_id', $category_id)->get();
return $products;
}
Api
Route::get('products/{category_id}', 'ProductsController@select_category');
When I delete $category_id
and where, only have like Products::all();
works fine, but need to specify where to search.
Link how I specify the $category_id is http://localhost:8000/api/products/?category_id=16
The log indicate that there is a route error, it has nothing to do with your Eloquent model
Check if you have another route conflicting with that one
Edit : After seeing your URL, you should use " http://localhost:8000/api/products/16 " rather than " http://localhost:8000/api/products/?category_id=16 "
The second one try to access your post route "Route::post('products'..." because, to Laravel, everything after the "?" is a parameter and isn't used in route detection
Make sure that in your routes file, below the definition of this route you don't have similar endpoint set for a post method. So you most probably have:
Route::post('products/something', 'ProductsController@store');
this will override the previously defined one.
To prevent this, you can modify your current route to this:
Route::get('products/{category_id}', 'ProductsController@select_category')->where('category_id', '[0-9]+');
change your URL:
http://localhost:8000/api/products/16
also change in a view file:
<a href="{{ URL::to('products/'. $yourchategoryid ) }}">product</a>
I think it should be
public function select_category(Request $request, $category_id){
$products = Products::where('category_id', $category_id)->get();
return $products;
}
if url is
http://localhost:8000/api/products/16
and if url is
http://localhost:8000/api/products/?category_id=16
function should be
public function select_category(Request $request){
$products = Products::where('category_id', $request->input('category_id'))->get();
return $products;
}
first parameter of the function should be Request
class instance
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.