我正在用Laravel编写端点。当我在Postman上进行测试时,出现此错误:
ErrorException:尝试获取文件C:\ xampp \ htdocs \ testing-file \ testing \ vendor \ laravel \ framework \ src \ Illuminate \ Http \ Resources \ DelegatesToResource.php中非对象的属性'id' 120
控制器
public function showBilling($id)
{
return new BillingResource($id);
}
型号
class Billing extends Model
{
protected $table = 'billing';
protected $fillable = [
'network' ,
'sender',
'recipient',
'message',
'timestamp',
'created_at',
'updated_at',
'amount',
'billing_type',
'user_id',
'service_name',
'package',
'email',
'user_id'
];
public function user() {
return $this->belongsTo('App\User');
}
}
资源
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
use App\Billing;
class BillingResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'network' => $this->network,
'sender' => $this->sender,
'recipient' => $this->recipient,
'message' => $this->message,
'amount' => $this->amount,
'billing_type' => $this->billing_type,
'email' => $this->email,
'user' => $this->user,
'service' => $this->service,
'package' => $this->package,
// Casting objects to string, to avoid receive create_at and update_at as object
'timestamp' => (string) $this->timestamp,
'created_at' => (string) $this->created_at,
'updated_at' => (string) $this->updated_at
];
}
}
如果我使用此GET请求:
应该显示受影响的行,但出现此错误:
ErrorException:尝试获取文件C:\ xampp \ htdocs \ testing-file \ testing \ vendor \ laravel \ framework \ src \ Illuminate \ Http \ Resources \ DelegatesToResource.php中非对象的属性“ id” 120
答案 0 :(得分:1)
尝试将模型提供给资源,而不仅仅是ID:
public function showBilling($id)
{
return new BillingResource(Billing::find($id));
}
您还可以按照Andrew G的建议使用路由模型绑定。
答案 1 :(得分:0)
您好,Mofolumike,欢迎您使用StackOverflow! 据我所知,问题在于路由模型绑定错误。您需要更改的只是:
public function showBilling(Billing $billing)
{
return new BillingResource($billing);
}
此外,您需要确保路由具有有效的参数名称。例如(routes / api.php):
Route::get('some/path/{billing}', 'BillingController@showBilling');
答案 2 :(得分:0)
尝试将模型提供给资源,而不仅仅是ID:
public function show($id)
{
return BillingResource::make(Billing::find($id));
}
public function show(Billing $billing)
{
return BillingResource::make($billing);
}
这是您的路线:
Route::get('/billings/{billing}','BillingController@show');