How to use foreach in the controller in Laravel

Limited Time Offer!

For Less Than the Cost of a Starbucks Coffee, Access All DevOpsSchool Videos on YouTube Unlimitedly.
Master DevOps, SRE, DevSecOps Skills!

Enroll Now
@foreach ($users as $user)
This is user {{ $user->id }}

@endforeach.
foreach ($items as $item) {
    echo $item;
}

// Using for loop
for ($i = 0; $i < count($items); $i++) {
    echo $items[$i];
}

Problem

I’m trying to loop over a request in the controller but i get this error:

"Trying to get property 'produit_id' of non-object"

here is the code

foreach( $request->livraison as $livraison) { 
   $produit = Produit::find($livraison->produit_id);
}
when i dd($request->livraison) i get this:

array:1 [
  0 => array:3 [
    "produit_id" => 1
    "quantite" => "43"
    "montant" => "65"
  ]
]

Solution:

$livraison is array not object

foreach( $request->livraison as $livraison)
{ 
        $produit = Produit::find($livraison['produit_id']);
}

Problem:

i have a problem about looping data in controller (laravel 4). my code is like this:

$owner = Input::get('owner');
$count = Input::get('count');
$product = Product::whereOwnerAndStatus($owner, 0)->take($count)->get();
when i want to use foreach to loop for $product result with code like this:

foreach ($product->sku as $sku) {
    // Code Here
}

the result is returning error Undefined property: Illuminate\Database\Eloquent\Collection::$sku

so, i try to improvise a little with this code:

foreach ($product as $items) {
    foreach ($items->sku as $sku) {
        // Code Here        
    }
}

Solution

This will throw an error:

foreach ($product->sku as $sku){ 
// Code Here
}
because you cannot loop a model with a specific column ($product->sku) from the table.
So, you must loop on the whole model:

foreach ($product as $p) {
// code
}
Inside the loop you can retrieve whatever column you want just adding ->[column_name]

foreach ($product as $p) {
echo $p->sku;
}

Get Data from foreach loop in controller

 $dis = array();
       foreach($countries as $key => $value){
           $dis[$key] = DB::table('divisions')->where('country_name', '=', $value->country_name)->get();
        }
$event_ids           = [];

              foreach($top_selling_trips as $key => $value)
              {
                  if($value->total_booking)
                      $event_ids[] = $value->id;
              }
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x