dimanche 9 juillet 2017

Storing a new post tag if it doesn't exist in the table?

I have a single input field (using select2 plugin) in a blog post form which allow user to insert post tags from existing tags in the table or create new ones and store them in the Tag table and also attach them to the post when they hit submit post button. I've managed to get this work by filtering the input with array_filter(), if the input is !is_numeric the input will first get stored in Tag table and then attach the id to the post.

The problem with this is that it's not working when the new tag from the input is in full numeric type, like 2017 tag. Is there a solution to get this working so the new tag is not limited to string only but also numeric type ? and if possible, I don't want to use any package for this.

The post store method :

public function store(PostsReq $request) {
        $input = $request->all();
        $post = Post::create($input);

        //Handle the tags
        $getTags = $request->input('tagspivot');
        $oldTags = array_filter($getTags, 'is_numeric');
        $newTags = array_filter($getTags, function($item) {
            return !is_numeric($item);
        });
        foreach ($newTags as $newTag) {
            if ($tag = Tag::create(['title' => strtolower(trim($newTag))])) {
                $oldTags[] = $tag->id;
            }
        }
        $post->tags()->attach($oldTags);

        // Upload Image
        if ($request->hasFile('image')) {
            $input['image'] = $this->uploadImage($request, $post);
        }
        return redirect()->route('postindex')->with($this->postStoreSuccess);
    }



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2u2Qm6f
via IFTTT

Aucun commentaire:

Enregistrer un commentaire