I have these:
posts table
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title', 64);
$table->string('teaser', 128)->nullable();
$table->text('content', 50000);
$table->timestamps();
});
}
posts model
use HasFactory;
protected $fillable = ['title', 'teaser', 'content'];
public function tags()
{
return $this->belongsToMany(Tag::class, 'post_tag', 'post_id', 'tag_id');
}
tag table
public function up()
{
Schema::create('tags', function (Blueprint $table) {
$table->id();
$table->string('text', 32);
});
}
tag model
use HasFactory;
public $timestamps = false;
public $fillable = ['text'];
public function posts()
{
return $this->belongsToMany(Post::class, 'post_tag', 'tag_id', 'post_id');
}
post_tag table
public function up()
{
Schema::create('post_tag', function (Blueprint $table) {
$table->id();
$table->unsignedInteger('post_id');
$table->unsignedInteger('tag_id');
});
}
When I try to create a new post with tags, I get this error:
SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect integer value: 'test' for column `laravel`.`post_tag`.`tag_id` at row 1
INSERT INTO
`post_tag` (`post_id`, `tag_id`)
VALUES
(31, test)
This is how I'm trying to do it:
public function store(PostFormValidation $request)
{
$newpost = Post::create($request->validated());
$newpost->tags()->sync($request->tags);
return redirect(route('home'));
}
But why is it complaining about the timestamps, when I removed them from the migration and specified that I'm not using any in the model too? What am I missing?
The submitted "tags" is a multiple select.
CodePudding user response:
You tyining instert in field tag_id 'test' word, but tag_id unsignedbiginteger
CodePudding user response:
I think your error is in:
$newpost->tags()->sync($request->tags);
I would recommend looking at this laravel doc to see that the format should be:
$newpost->tags()->sync([1, 2, 3]);
Or:
$newpost->tags()->sync([1 => ['expires' => true], 2, 3]);