How to use foreach in the controller in Laravel

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

foreach ($items as $item) {
    echo $item;

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


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"


$livraison is array not object

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


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        


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)
                      $event_ids[] = $value->id;
Notify of

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

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x