【发布时间】:2021-06-27 09:59:56
【问题描述】:
我创建了一个 Laravel API 端点 api/post/offer,它将在其中创建一个帖子。
使用邮递员的邮寄请求。
postman post request
然后会访问api.php处的路由
Route::post('post/offer', [PostController::class, 'create_offer_post'])->name('create_offer_post');
在我的 PostController 中使用 create_offer_post 方法
public function create_offer_post(Request $request) {
//validate data
$request->validate([
'email' => ['required', 'email', 'max:50'],
'postIdentity' => ['required', 'max:100'],
'postStatus' => ['required', 'max:50'],
'deliveryArea' => ['required', 'max:500'],
'shoppingPlace' => ['required', 'max:2000'],
'deliverySchedule' => ['required', 'date'],
'transportMode' => ['required', 'max:200'],
'capacity' => ['required', 'max:100'],
'paymentMethod' => ['required', 'max:200'],
'caption' => ['required', 'max:200'],
'isLoggedIn' => ['required', 'boolean']
]);
dd($request->all());
// if logged in create offer post
if($request->isLoggedIn) {
DB::transaction(function () {
$post = new Post;
$post->email = $request->email;
$post->postIdentity = $request->postIdentity;
$post->postStatus = $request->postStatus;
$post->save();
$offer_post = new OfferPost;
$offer_post->postStatus = $request->postStatus;
$offer_post->deliveryArea = $request->deliveryArea;
$offer_post->shoppingPlace = $request->shoppingPlace;
$offer_post->deliverySchedule = $request->deliverySchedule;
$offer_post->transportMode = $request->transportMode;
$offer_post->capacity = $request->capacity;
$offer_post->paymentMethod = $request->paymentMethod;
$offer_post->caption = $offer_post->caption;
$post->offer_post()->save($offer_post);
});
return response()->json(['message' => 'Offer post successfully created.'], 201);
}
else {
return response->json(['error' => 'You are not logged in.'], 401);
}
}
它验证请求。然后它应该将帖子保存在数据库中。
我的问题是每当我在邮递员中发送请求时。它发送一个 200 响应代码。我期待 201 或 401 响应代码。但我收到 200 响应代码,并且数据库中没有保存新记录。 dd() 也不工作
【问题讨论】:
-
可能你错过了一些你在模型中使用的属性,匹配属性而不是你也可以使用的,资源丰富的 API 模式laravel.com/docs/8.x/eloquent-resources