Laravel attach detach and sync methods
Posted 5 years ago by Ryan Dhungel
Category: Laravel
Viewed 23799 times
Estimated read time: 10 seconds
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]);