I have a many-to-many relationship between users and products. When the user doesn't have an account or is not logged in we save their products (cart) to a cookie. So I have a 'cartProducts' cookie that looks like [['id' => 1, 'quantity' => 2], ...]. We then new-up a user and attach the products to the user that only exists in memory so we can send it to the same view that I send a normal user to.
$productsArray = Cookie::get('cartProducts');
$user = (new User);
foreach($productsArray as $product) {
$user->cartProducts()->attach(
$product['product_id'],
['quantity' => $product['quantity']]
);
}
This works fine but it saves to the pivot with a null user_id. We don't need to store this in the database. How can I attach it to the object so it can be used in a view without saving to the database?
Thanks for the response. I can build it out using setRelation in combination with creating the collections and all but this still leaves me jumping through hoops. I need this to have all the functionality of a normal relationship.
I only have the id and quantity in the cookie so I can't use just hydrate. I could do something complex like create the products and loop over them to create the relationship with the mock pivot and all. It just seems like there should be an easy way to do the attach without writing to the database.
@DutGRIFF Eloquent doesn't store any references about the relations between models (unlike eg. Doctrine), so technically there is no m-m relation unless it is stored in the pivot table.
What do you need it for exactly? What normal relationship stuff will you do?
I ended up doing something really hacky which included creating a collection and attaching all of the products and pivots to make an identical collection to the one that is normally passed to the views. Here it is as of now:
$productsArray = Cookie::get('cartProducts');
$user = (new User);
$productsCollection = collect();
foreach($productsArray as $prod) {
// Here we fake the attach of product to user for each product
$product = Product::find($prod['product_id']);
$pivot = $product->newPivot($user, $prod, 'carts', true);
$product->setRelation('pivot', $pivot);
$productsCollection->push($product);
}
$user->setRelation('cartProducts', $productsCollection);
$products = $user->cartProducts;
//render the view passing in the $products variable
@JarekTkaczyk I know there wouldn't be the actual relationship but I want a collection identical to the one built when I do $products = Auth::user()->cartProducts;. In the view right now I use the products properties and a property on the pivot: