Am使用using与Laravel编写端点。当我使用POST方法在邮递员上进行测试时,出现此错误:
ErrorException:尝试在第912行的文件C:\ xampp \ htdocs \ testing-file \ testing \ app \ Http \ Controllers \ ApiController.php中获取非对象的属性'id'
控制器
public function storeBilling(Request $request)
{
// $billing = Billing::create($request->all());
// return response()->json(['success' => $billing], $this-> successStatus);
$validator = Validator::make($request->all(), [
'network' => 'required'
]);
if ($validator->fails()) {
return response()->json($validator->errors(), 422);
}
// Creating a record in a different way
$createBilling = Billing::create([
'user_id' => $request->user()->id,
'network' => $request->network,
'sender' => $request->sender,
'recipient' => $request->recipient,
'message' => $request->message,
'amount' => $request->amount,
'billing_type' => $request->billing_type,
]);
return new BillingResource($createBilling);
}
型号
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
];
}
}
如果我使用此POST方法:
http://localhost/testing-file/stesting/api/storeBilling?network=100
它应该发布到数据库中,但出现此错误:
ErrorException:尝试在第912行的文件C:\ xampp \ htdocs \ testing-file \ testing \ app \ Http \ Controllers \ ApiController.php中获取非对象的属性'id'
答案 0 :(得分:0)
'user_id' => $request->user()->id
您的错误是说$request->user()
不是对象,因此您无法使用对象表示法(例如)访问其参数。 ->id
。
如果您dd($request->user)
可能会发现您没有得到自己想要的结果-它可能是数组,或者根本不是正确的值。
如果它是一个数组,则可以访问类似$request['user']['id']
的值。这实际上取决于您在POST请求中传递的内容。
答案 1 :(得分:0)
$request->user()->id
不正确。
如果希望当前用户可以使用Auth::user()
。
答案 2 :(得分:0)
在你身上
公共功能storeBilling(Request $ request)
您写了\d{2}(\d{2})?
,并且此创建错误。
或者更可取的是让$createBilling = Billing::create([
'user_id' => $request->user()->id,
查找经过身份验证的用户的ID。
不要忘记在控制器的开头添加$createBilling = Billing::create([
'user_id' => Auth::user()->id,
答案 3 :(得分:0)
在问题的开头,您说过您正在尝试使用Lravel建立端点。
除非通过身份验证,否则邮递员将无法访问用户对象,如果通过身份验证,则应该可以使用::
$request->user()->id or Auth::user()->id or $request["user"]["id"]