Laravel attach detach and sync methods

Posted 2 years ago by Ryan Dhungel

Category: Laravel

Viewed 13444 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;
// category_id and product_id are set in pivot table
// using belongsToMany relationship
$category = Category::find(3);

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

To remove a product from category using detach method


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