class Post extends Model
{
protected $casts = [
'tags' => 'array',
];
}
public function store()
{
$tags = [];
if (!empty($_POST['tags'])) {
foreach ($_POST['tags'] as $tag) {
array_push($tags, $tag);
}
dd($tags);
}
$this->validate(request(), [
'title' => 'required',
'body' => 'required',
//'tags' => 'nullable|array'
]);
$post = Post::create([
'title' => request('title'),
'body' => request('body'),
'user_id' => auth()->id(),
'tags' => $tags
]);
session()->flash('message', 'Your post has been published!');
return redirect('/');
}
Sep 14, 2017
4
Level 2
Adding Tags to Posts in Store Method
I have a form with input fields for 'title' and 'body', and checkbox inputs for 'tags'. I'm trying to attach the tags to the post in the store method of the PostsController. At this point, I am able to collect the chosen tags into an array, but I'm not sure how to attach them to the post. Here is my store method:
public function store()
{
$tags = [];
if (!empty($_POST['tags'])) {
foreach ($_POST['tags'] as $tag) {
array_push($tags, $tag);
}
dd($tags);
}
$this->validate(request(), [
'title' => 'required',
'body' => 'required',
// 'tag' => 'nullable|string'
]);
$post = Post::create([
'title' => request('title'),
'body' => request('body'),
'user_id' => auth()->id()
]);
session()->flash('message', 'Your post has been published!');
return redirect('/');
}
I'm trying to figure out how to attach the array of tags to the created post.
Any help is very appreciated. Thanks :-)
Please or to participate in this conversation.