dimanche 19 juin 2016

Trying to create a tag system in laravel

I am trying to create a tag system for my own usage but I have got some problems with it

here is my code :

 public function postAddPost(Request $request){
    $post = new Post;
    $post->user_id = $request->user_id;
    $post->content = $request->content;
    $post->status = 1;
    $post->save();
    $hashtag_string = $request->tags;
    $postlast=Post::orderby('id','dsc')->first();

    $matches=explode(',',$hashtag_string);
    //looping through matched items in your $matches array
    foreach($matches as $tags)
    {
      $tag = new Tag;
      $tag->post_id = 0;
      $tag->tagname = $tags;
      $tag->save();
    }
    Session::flash('message','Post added');
    return redirect('/admin/posts');
}

but the problem is it gives me this error

 SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`test`.`tags`, CONSTRAINT `tags_post_id_foreign` FOREIGN KEY (`post_id`) REFERENCES `posts` (`id`)) (SQL: insert into `tags` (`post_id`, `tagname`, `updated_at`, `created_at`) values (0, #hello, 2016-06-19 07:12:37, 2016-06-19 07:12:37))

i know that the problem is i am trying to attach the tag to a post_id which hasn't been created yet but how can i create post with post_id before tag get created? thanks



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire