在 laravel8 中发布请求不起作用

时间:2021-03-22 06:12:51

标签: post laravel-8 restapi

获取请求工作正常。但是当我尝试通过 POST 请求创建帖子时,它给出了以下错误....

Illuminate\Database\QueryException: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'title' cannot be null (SQL: insert into `posts` (`title`, `content`, `updated_at`, `created_at`) values (?, ?, 2021-03-22 06:05:00, 2021-03-22 06:05:00))

这是我的数据库表名:id title content created_at

后模型:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use HasFactory;

    protected $table="posts";

    protected $fillable=[

        "title",
        "content"
    ];

};

数据库:

public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->id();
        $table->string('title');
        $table->text('content');
        $table->timestamps();
    });
}

api 路由:

    Route::get('/posts', function(){

    return Post::all();
});

Route::post('/posts', function(){
    
return Post::create([

 "title" => request('title'),
 "content" => request('content'),
 ]);

});

1 个答案:

答案 0 :(得分:0)

我建议您检查是否从 request() 方法接收到正确的数据

Route::post('/posts', function(){
   dd(request('title'));

你可以尝试的另一种方式是

Route::post('/posts', function(Request $request){
    
return Post::create([

 "title" => $request->get('title'),
 "content" => $request->get('content'),
 ]);

});

问候