Laravel attach detach and sync methods


Posted 3 months ago | by Ryan Dhungel | on Laravel  | Viewed 540 times

Understand attach detach and sync methods, provided by laravel with simpler and practical examples.

Using attach method in Laravel

Route::get('/', function(){
$product = new Product;
$product->title = 'Cap';
$product->price = 50;
$product->save();
// category_id and product_id are set in pivot table
// using belongsToMany relationship
$category = Category::find(3);
$product->categories()->attach($category);
});

Saving product in multiple categories

$category = Category::whereIn('title', ['Food', 'Fashion'])->get();
// Find a product and category and make changes using the same attach method
$product = Product::find(1);
$category = Category::find(2);
$product->categories()->attach($category);

To remove a product from category using detach method

$product->categories()->detach($category);

Sync products to a category using sync method

$category = Category::find(2);
// products with the id of 3 and 4 are to sync with the given categorye
$category->products()->sync([3,4]);


Specials


Build Laravel React CRUD/SPA APP in 2 hours
Build Laravel React CRUD/SPA APP in 2 hours

Build Laravel React CRUD/SPA APP in 2 hours

COUPON CODE: REACTCRUD with 90% off


Laravel with React JS - Build Twitter Like Real Ti...
Laravel with React JS - Build Twitter Like Real Time Web App

Laravel with React JS - Build Twitter Like Real Time Web App

COUPON CODE: LARAVELREACT with 90% off


Learn Laravel Building Multi User Blogging Platfor...
Learn Laravel Building Multi User Blogging Platform with SEO


React Redux Firebase CRUD App with Authentication
React Redux Firebase CRUD App with Authentication

React Redux Firebase CRUD App with Authentication

COUPON CODE: RRFTEN with 86% off


Become a Master of JavaScript from Scratch in 2018
Become a Master of JavaScript from Scratch in 2018

Become a Master of JavaScript from Scratch in 2018

COUPON CODE: JSMASTERSALE with 92% off


REACT - Up and Running with React ES6 and Open Sou...
REACT - Up and Running with React ES6 and Open Source API


Sublime Text for Rapid Web Development
Sublime Text for Rapid Web Development

Sublime Text for Rapid Web Development

COUPON CODE: LEARNSUBLIME with 90% off