I have a blog where you can select multiple tags for the post, it is returning the multiple selections, but as strings instead of the id. Not sure why and my searches have not helped me either.
Migration
public function up()
{
Schema::create('post_tag', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('post_id');
$table->integer('tag_id');
});
}
Controller Store function
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(CreatePostsRequest $request)
{
// upload image
$image = $request->image->store('posts');
dd($request->all());
$post = Post::create([
'title' => $request->title,
'description' => $request->description,
'content' => $request->content,
'image' => $image,
'published_at' => $request->published_at,
'category_id' => $request->category,
]);
if ($request->tags) {
$post->tags()->attach($request->tags);
}
session()->flash('success', 'Post created.');
return redirect(route('posts.index'));
}
View
<div class="form-group">
<label for="category">Category</label>
<select id="category" class="form-control" name="category">
@foreach($categories as $category)
<option value="{{ $category->id }}"
@if(isset($post))
@if($category->id === $post->category_id)
selected
@endif
@endif
>{{ $category->name }}</option>
@endforeach
</select>
</div>
@if ($tags->count() > 0 )
<div class="form-group">
<label for="tags">Tags</label>
<select name="tags[]" id="tags" class="form-control" multiple>
@foreach ($tags as $tag)
<option vlaue="{{ $tag->id }}"
@if(isset($post))
@if($post->hasTag($tag->id))
selected
@endif
@endif
>{{ $tag->name }}</option>
@endforeach
</select>
</div>
@endif
<div class="form-group">
<button class="btn btn-success" type="submit">
{{ isset($post) ? 'Update Post' : 'Create post' }}
</button>
DD dump in the browser
array:8 [▼
"_token" => "BhvnTsZ0XCmdGo9LKDWtpJb5Rhc0kQiDrP7Ae9kN"
"title" => "Laravel install on windows server"
"description" => "dsfgsfgsdg"
"content" => "<div>dsfgdsfgdsfg</div>"
"published_at" => "2019-11-04 12:00"
"category" => "3"
"tags" => array:2 [▼
0 => "laravel"
1 => "laracasts"
]
"image" => UploadedFile {#288 ▶}
]
Laravel should be 0 and laracasts should be a 1 to be sent to the post_tag table and laravel is giving me this error:
SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect integer value: 'laravel' for column qq.post_tag.tag_id at row 1 (SQL: insert into post_tag (post_id, tag_id) values (2, laravel), (2, laracasts))
Not sure what I am missing