laravel控制器
public function getbrands(Request $request)
{
$id = DB::table('products')->where('product', '=',$request->product)->first()->id;
$brands = Product::find($id)->brands;
return response()->json($brands);
}
这就是我在Postman中得到的东西
[
{
"id": 2,
"brand": "Bluemount",
"pivot": {
"product_id": 2,
"brand_id": 2
}
},
{
"id": 3,
"brand": "LG",
"pivot": {
"product_id": 2,
"brand_id": 3
}
}
]
但我在Ionic App中遇到错误
{…}
_body: "{\"message\":\"Trying to get property of non-object\",\"status_code\":500}"
headers: Object { _headers: Map, _normalizedNames: Map }
ok: false
status: 500
statusText: "Internal Server Error"
type: 2
url: "http://127.0.0.1:8000/api/getbrands"
__proto__: Object { constructor: Response(), toString: Response.prototype.toString() }
call.ts:143:10
Dismissed toast
但是当我在getBrands函数中将$ request-> product更改为'RO'时,如下所示
public function getbrands(Request $request)
{
$id = DB::table('products')->where('product', '=','RO')->first()->id;
$brands = Product::find($id)->brands;
return response()->json($brands);
}
然后我在离子应用程序中获取数据。你好错了
首先确保您的请求标头包含:
Content-Type:Application/json
和Accept: application/json
“试图获取非对象的属性”,“status_code”:500
这个错误正在发生,因为$request->product
,product
参数它没有在请求对象中提供因此laravel squawks。因此,请确保当您向api提出请求时,请提供product
url参数!
我很确定如果您将此代码添加到您的方法中,您将得到响应:产品未在请求中提供!
public function getbrands(Request $request)
{
if(!request()->has('product'))
{
return response(['message'=>'Product not provided in request'], 402);
}
$id = DB::table('products')->where('product', '=','RO')->first()->id;
$brands = Product::find($id)->brands;
return response()->json($brands);
}
无论请求数据是否正确到达,这似乎都不是,您在这里使用结果的方式存在问题。
在这种情况下,您正在运行可能返回空结果的查询null
。你需要检查这些。如果与请求一起发送了无效的product
,则最终会出现错误,因为在尝试使用这些结果之前,您没有检查这些查询的结果是否实际返回了任何内容。
// could return a null
DB::table('products')->where('product', '=',$request->product)->first();
// also could return a null
Product::find($id);