【问题标题】:There is nothing happening when store data for Laravel API为 Laravel API 存储数据时没有任何反应
【发布时间】:2021-02-14 18:15:01
【问题描述】:

我制作 laravel API,我可以在其中存储一个新数据,其中的值是 body raw json 中的值。但是当我尝试使用 post 发送请求时,除了状态为 200 OK,我什么也没得到。当我检查我的 mysql 时,没有输入数据。 那么,我该怎么办?

mysql 数据

Laravel 控制器和 API,

// function in controller
use App\Models\ChartAge;
class ChartController extends Controller
{
   public function saveChart(Request $request)
   {
    $data = $request->validate([
        'entity' => 'required|string|max:10',
        'code' => 'required|string|max:10',
        'year' => 'required|int|max:10',
        'under_age_15' => 'required|string|max:50',
        'age_15_64' => 'required|string|max:50',
        'age_65_over' => 'required|string|max:50',
    ]);

    $values = ChartAge::create($request);

    return response()->json(
        [
            'status' => true,
            'message' => "the videos has been favorites",
            'data' => $values,
        ],
        201
    );
   }
}
//in api.php
Route::post("charts", [ChartController::class, 'saveChart']);

这是我尝试使用邮递员发送请求的时候。

因为没有报错,不知道怎么回事??

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    首先仔细检查您的 ChartAge 模型,它是否具有 $fillable 或没有?

    并编辑您的代码:

    来自

    $values = ChartAge::create($request);
    

    收件人:

    $values = ChartAge::create($request->all());
    

    希望这会有用。

    有验证:

    $data = \Validator::make($request->all(),[
        'entity' => 'required|string|max:10',
        'code' => 'required|string|max:10',
        'year' => 'required|int|max:10',
        'under_age_15' => 'required|string|max:50',
        'age_15_64' => 'required|string|max:50',
        'age_65_over' => 'required|string|max:50',
    ]);
    
    if($data-> fails()){
      return back()->withErrors($data)->withInput();
    }
    
    $values = ChartAge::create($request->all());
    

    【讨论】:

    • 它是这样工作的,但是,验证将被跳过,有没有办法我也可以使用验证?
    【解决方案2】:

    您是否在“ChartAge”模型中设置了可填写字段? protected $fillable = ['entity','code','year'...]; 您是否尝试通过禁用验证来测试代码? 请尝试将 dd($request) 放在控制器代码的第一行。

    方法 create 需要一个普通的 PHP 数组,而不是 Request 对象。

    【讨论】:

    • 是的,我已经这样做了很多次了,我应该编辑我的帖子并放置我的图表模型吗?是的,我在使用请求转储数据请求禁用验证时测试代码,该值正在显示。但是当我评论倾销时,它的反应是 200 好的。仍然不知道那里发生了什么
    • 我认为您应该通过仅传递具有此函数预期值的普通 PHP 数组来测试函数 ChartAge::create()。 $data = [ '实体' => '测试值', '代码' => '测试', '年份' => '测试', 'under_age_15' => '测试', 'age_15_64' => '测试', 'age_65_over' => '测试', ]); ChartAge::create($data) 因为在你的代码中是 ChartAge::create($request) 而不是 ChartAge::create($data)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-16
    • 2017-07-14
    • 2018-12-22
    • 2015-01-26
    • 2013-10-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多