我只是不知道这是怎么发生的。用户输入文本后,它将文本的两个副本发送到数据库,而不是一个。我很确定我的代码是正确的,但是不确定为什么它会在数据库中发送用户输入的重复副本。
我在做什么错了?
这是我的create_posts_table
在迁移文件夹中:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePostsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('body', 140);
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('posts');
}
}
发布到数据库:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Post;
class PostController extends Controller
{
public function create(Request $request, Post $post) {
// create post
$createdPost = $request->user()->posts()->create([
'body' => $request->body
]);
// return response
return response()->json($post->with('user')->find($createdPost->id));
}
}