Send Data To Pivot Table

$post->update();

// category and ppost data goes to pivot table [category_post],[post_tag] table

$post->categories()->attach($request->categories); //  $post->categories() = categories function in post model

$post->tags()->attach($request->tags); //  $post->tags() = tagsfunction in post model

session()->flash('msg', 'Successfully Update Post');

return redirect()->back();

 

Update Data In Pivot table [sync($request->tags)]

Using the flowing function in your controller Sync the pivot table data

$post->update();

        // category and post data goes to pivot table [category_post],[post_tag] table

        $post->categories()->sync($request->categories);

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

 

Note: Send Data to pivot table after send data to main table . send pivot table data after “update(), save()” Function

 

Delete Pivot Databe Data when delete its parent

PostController

public function destroy($id)

    {

        $post= Post::find($id);

        $post->categories()->detach(); // delete with many to many relationship

        $post->tags()->detach();

        $post->delete();

        return back()->with('msg', 'Post Has Been Deleted');

    }

 

Cmd : php artisan make:migration create_category_post --table=category_post (alphabetical order)

On Delete Cascade function in model

When Delete data from main table like, I am delete a post from posts table, But Posts_tags table store the tag id and post id. To solve the problem use onDelete cascade function

Posts table

 public function up()

    {

        Schema::create('posts', function (Blueprint $table) {

            $table->increments('id');

            $table->integer('user_id')->unsigned(); // foreign key 

            $table->string('title');

            $table->string('slug')->unique();          

            $table->string('image')->default('default.jpg');

            $table->text('body');

            $table->integer('view_count')->default(0);    

            $table->boolean('status')->default(false);

            $table->boolean('is_approved')->default(false);  

            // When Delete an user delete the row delete the post where user_id=delete user id

            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); 

            $table->timestamps();

        });

    }

Create Pivot Table using laravel package

for the latest Laravel's versions:

composer require --dev laracasts/generators

php artisan make:migration:pivot table1 table2