skip to Main Content
//Post Model

class Post extends Model
{

    use HasFactory;

    //for Tag Relation
    public function tags(){
        return $this->belongsToMany(Tag::class ,'post_tag');
    }
    
}
//Tag model

class Tag extends Model
{
    use HasFactory;
   
    // for Post Relation
    public function posts(){
        return $this->belongsToMany(Post::class, 'post_tag');
    }
}
// And PostController Store data into database function code 

 public function store(Request $request)
    {        
       
       // dd($request);
        //form validation
        $this->validate($request,[
            'title' => 'required|max:60',
            'slug' => 'required|min:5|max:255|alpha_dash|unique:posts,slug',
            'category_id' => 'required|integer',
            'body' => 'required'
        ]);

        // store into database
        $Post = new Post();
        

        $Post->title = $request->title;
        $Post->slug = $request->slug;
        $Post->category_id = $request->category_id;
        $Post->body = $request->body;

        $Post->save();
        $Post->tags()->sync($request->tags);
        Session::flash('success', 'The Blog Post was Successfully save');
        // to redirect to other page
        return redirect()->route('post.show',$Post->id);
    }

2

Answers


  1. For store data, use

    $Post->tags()->attach($request->tags);
    

    For updates, use

    $Post->tags()-> sync($request->tags);
    

    Details Here

    Also here

    Login or Signup to reply.
  2. Try below

    public function store(Request $request) 
    {
    
       // dd($request);
        //form validation
        $validatedAttributes = $this->validate($request,[
            'title' => 'required|max:60',
            'slug' => 'required|min:5|max:255|alpha_dash|unique:posts,slug',
            'category_id' => 'required|integer',
            'body' => 'required'
        ]);
    
        // store into database
        $Post = Post::create($validatedAttributes);
    
        $Post->tags()->sync($request->tags);
    
        Session::flash('success', 'The Blog Post was Successfully save');
    
        // to redirect to other page
        return redirect()->route('post.show',$Post->id);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search