Laravel API中store方法无法插入数据,请求连接被拒绝问题求助
问题排查与修复方案
1. 路由错误:请求地址不正确
你使用Route::apiResources注册资源路由,对应的store方法路由是POST /api/blood_type,而非你请求的/api/store。Laravel资源路由默认规则如下:
- POST
/api/blood_type→ store方法 - GET
/api/blood_type→ index方法 - GET
/api/blood_type/{blood_type}→ show方法 - PUT/PATCH
/api/blood_type/{blood_type}→ update方法 - DELETE
/api/blood_type/{blood_type}→ destroy方法
请在Postman中把请求地址改为POST http://localhost:8000/api/blood_type。
2. 请求参数位置错误
从报错信息看到你把description放在了请求头里,但代码是从请求体获取参数。需要将description移到Postman的请求体中:
- 选择
Body标签 - 切换为
raw格式,类型选JSON - 输入参数内容:
{ "description": "A+" }
3. 代码中的语法错误
(1) store方法变量名错误
store方法最后返回的$tipo_hunter未定义,应改为创建好的$type_blood:
// 错误代码 return response()->json($tipo_hunter, 201); // 修正后 return response()->json($type_blood, 201);
(2) update方法模型名错误
update方法错误使用了TypeBloodModelModel,正确模型名是TypeBloodModel:
// 错误代码 $type_blood = TypeBloodModelModel::where('id', $id)->update($treated_datas); // 修正后 $type_blood = TypeBloodModel::findOrFail($id); $type_blood->update($treated_datas);
(3) update方法返回变量错误
update方法返回的$tipo_hunter未定义,建议返回更新后的模型数据:
// 错误代码 return response()->json($tipo_hunter, 201); // 修正后 return response()->json($type_blood, 200);
4. 模型批量赋值权限
确保TypeBloodModel中设置$fillable属性,允许description字段批量赋值,否则create和update方法会因批量赋值保护失败:
// app/Models/TypeBloodModel.php class TypeBloodModel extends Model { protected $fillable = ['description']; // 添加该行 // 其他代码... }
5. 服务连接问题排查
如果上述修正后仍出现ECONNREFUSED错误,重新确认Laravel服务状态:
- 关闭当前服务,重新执行
php artisan serve - 检查终端输出的服务地址是否为
http://localhost:8000,若端口不同,Postman请求地址需对应修改
修正后的TypeBloodController代码
<?php namespace App\Http\Controllers; use App\Http\Requests\TypeBloodRequest; use App\Models\TypeBloodModel; use Illuminate\Http\Request; class TypeBloodController extends Controller { public function index() { $type_blood = TypeBloodModel::all(); return response()->json($type_blood, 200); } public function store(TypeBloodRequest $request) { $validations = $request->validated(); $treated_datas = [ 'description' => trim((string) $validations['description']), ]; $type_blood = TypeBloodModel::create($treated_datas); return response()->json($type_blood, 201); } public function show($id) { $type_blood = TypeBloodModel::find($id); if (!$type_blood) { return response()->json(['message' => 'Resource not found'], 404); } return response()->json($type_blood, 200); } public function update(TypeBloodRequest $request, $id) { $validations = $request->validated(); $treated_datas = [ 'description' => trim((string) $validations['description']), ]; $type_blood = TypeBloodModel::findOrFail($id); $type_blood->update($treated_datas); return response()->json($type_blood, 200); } public function destroy($id) { TypeBloodModel::where('id', $id)->delete(); return response()->json(null, 204); } }
内容的提问来源于stack exchange,提问作者user22236733
相关产品推荐
相关产品推荐

