Home > Software engineering >  store data into pivot table laravel
store data into pivot table laravel

Time:06-05

//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);
    }

CodePudding user response:

For store data, use

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

For updates, use

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

Details Here

Also here

CodePudding user response:

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);
}
  • Related