1

order model product model

its a simple query in a controller using Order model:

$orders = Order::where('user_id', auth()->user()->id)
                        ->orderBy('created_at', 'desc')
                        ->get();
return dd($orders);

dd gives following results: (which is correct)

Collection {#269 ▼
  #items: array:2 [▼
    0 => Order {#270 ▼
      #dates: array:1 [▶]
      #fillable: array:6 [▶]
      #connection: "mysql"
      #table: null
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:9 [▶]
      #original: array:9 [▶]
      #changes: []
      #casts: []
      #dateFormat: null
      #appends: []
      #dispatchesEvents: []
      #observables: []
      #relations: []
      #touches: []
      +timestamps: true
      #hidden: []
      #visible: []
      #guarded: array:1 [▶]
      #forceDeleting: false
    }
    1 => Order {#271 ▼
      #dates: array:1 [▶]
      #fillable: array:6 [▶]
      #connection: "mysql"
      #table: null
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:9 [▶]
      #original: array:9 [▶]
      #changes: []
      #casts: []
      #dateFormat: null
      #appends: []
      #dispatchesEvents: []
      #observables: []
      #relations: []
      #touches: []
      +timestamps: true
      #hidden: []
      #visible: []
      #guarded: array:1 [▶]
      #forceDeleting: false
    }
  ]
}

but when i iterate through the $orders collection foreach loop, only the first array is is shown, the second array is not accessible... whats wrong with foreach loop... ?

$temp='';
        foreach($orders as $order){
                $temp.= $order->product; // accessing the belongTo method
        }

        dd($temp);

here is the output (only one array is shown):

"{"id":13,"created_at":"2018-06-06 15:28:21","updated_at":"2018-06-06 18:36:28","type":0,"title":"product 3","description":"this is product no 3 with 5 images","images":"night-product-watch-dramatic-84475_1528310188.jpeg,night-product-watch-dramatic-84475_1528310188.jpeg","alive":1,"user_id":1,"deleted_at":null} ◀"
12
  • Show you model definition. Commented Jun 8, 2018 at 15:26
  • class Product extends Model { use SoftDeletes; /** * The attributes that should be mutated to dates. * * @var array */ protected $dates = ['deleted_at']; Protected $fillable= ['title', 'type', 'description','images','alive']; public function user(){ return $this->belongsTo('App\User'); } public function orders(){ return $this->hasMany('App\Order'); } } Commented Jun 8, 2018 at 15:49
  • class Order extends Model { use SoftDeletes; /** * The attributes that should be mutated to dates. * * @var array */ protected $dates = ['deleted_at']; Protected $fillable= ['comments', 'product_id', 'type', 'user_id', 'alive', 'granted']; public function user(){ return $this->belongsTo('App\User'); } public function product(){ return $this->belongsTo('App\Product'); } } Commented Jun 8, 2018 at 15:50
  • can you var_dump($order) so you see what is the output of the second order? Inside foreach I mean Commented Jun 8, 2018 at 16:37
  • Foreach is correct it's just you tripping I think X) Commented Jun 8, 2018 at 16:40

2 Answers 2

1

If you are building an array of products across all orders you cannot use string concatenation. Use an array and push items onto it.

$products = [];
foreach ($orders as $order) {
    if ($order->product) {
        $products[] = $order->product;
    }
}
dd($products); // will be an array of all other products.
Sign up to request clarification or add additional context in comments.

4 Comments

thanks, but this still does gives the second array item as null... here is the output of dd... array:2 [▼ 0 => Product {#276 ▶} 1 => null ] i just wonder whats wrong with foreach loop... or am i missing something here...
The null item for the second item means the Product is not defined. I updated the code to avoid that
this is not the issue... i am also getting the same results see dd($temp); in question. foreach loop suppose to loop through exactly 2 products. and currently i don't know why it loops through the first one successfully but for the second iteration it gives null... (both products exists) i think its something to do with laravel collections... may be im not properly iterating through the collection...
no change in code... upto this point the code in my question and your answer both gives the same result... but both miss the second item in collection... which is the real question?
0

Try this:

$temp= [];
foreach($orders->all() as $order){
     $temp[] = $order->product;
}

And you may edit your query

$orders = Order::where('user_id', auth()->user()->id)
                    ->with('products')
                    ->orderBy('created_at', 'desc')
                    ->get();

2 Comments

the $temp[] code gives no output just blank screen, while if i use with('products') in query it gives error: Call to undefined relationship [products] on model [App\Order]. (relationship is defined in order as it belongs to many products, while in product it has many orders)...
$orders = Order::where('user_id', auth()->user()->id) ->orderBy('created_at', 'desc') ->get(); $temp=[]; foreach($orders as $order){ $temp[]= $order->product; } dd($temp); gives following the same output, only first item is shown, and null is shown for second item... array:2 [▼ 0 => Product {#276 ▶} 1 => null ]

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.