1

How to allow only one set of data from an array in Laravel-5.4 controller:

foreach(Cart::content() as $cartitem) {
   if($cartitem->id === $id){
      do something....
   }
}

I want to take only the set of data from $cartitem when $cartitem->id === $id ($id is coming from request) and reject all other set of data from $cartitem. Set of data can be found anywhere (in any index) from the array.

5
  • can you show how your array look like? Commented Nov 2, 2017 at 10:24
  • Cart::content() where you get this?? Commented Nov 2, 2017 at 10:24
  • @MahfuzShishir I am using LaravelShoppingcart package. Commented Nov 2, 2017 at 10:29
  • This method will return a Collection of CartItems which you can iterate. But one thing you have to remember. your collection contain any id object? Commented Nov 2, 2017 at 10:33
  • @urfusion its in object format, in in chrome jsonview-> {rowId:"8b523dd15035cdcb4ef379230ba71cd8",id: "2",name: "Beam 2",qty: 3,price: 45,options: {image: /images/products/default_product.png",available_quantity: 3},tax: 9.45,subtotal: 135}} Commented Nov 2, 2017 at 10:34

2 Answers 2

4

You can use where() of eloquent to achieve the same.

Cart::content()->where('id', $id);
Sign up to request clarification or add additional context in comments.

4 Comments

Did the tricks for me! Thank you so much. Did not realize Cart will support the ->where() query. You are genius!
I wish I could that but my poor reputation is not allowing me :( but once my reputation increased i'll for sure.
@WasidHossain You can't maybr upvote but you should be able to accept answer as correct.
Done, sorry I thought accepting and voting up is the same :D
1

I would recommend that in the request you already query for that specific id from cart. This way you don't need this foreach loop.

foreach(Cart::content() as $cartitem) {
   if($cartitem->id === $id){
      $cartitem; // this is your item
      break; // break from loop you found it already so stop looping
   }
}

From the documentation you can use: (returns all items with id = 1)

$cart->search(function ($cartItem, $rowId) {
    return $cartItem->id === 1; // this will return all items with id = 1
});

Or get by rowId

$rowId = 'da39a3ee5e6b4b0d3255bfef95601890afd80709'; // this is just demo code
Cart::get($rowId);

1 Comment

actually here I had to check with the available product's id from DB with the current Cart which would never match with "rowId" so I had to match with cart's saved 'id'. and also maintain all the cart in one view for all products.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.