πŸš€ DevOps Certified Professional
πŸ“… Starting: 1st of Every Month 🀝 +91 8409492687 | 🀝 +1 (469) 756-6329 πŸ” Contact@DevOpsSchool.com

How to use foreach in the controller in Laravel.

DevOps

Upgrade & Secure Your Future with DevOps, SRE, DevSecOps, MLOps!

We spend hours on Instagram and YouTube and waste money on coffee and fast food, but won’t spend 30 minutes a day learning skills to boost our careers.
Master in DevOps, SRE, DevSecOps & MLOps!

Learn from Guru Rajesh Kumar and double your salary in just one year.


Get Started 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

When I try to loop over a request in the controller, I receive the following 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’m having trouble with the Laravel 4 controller’s data looping. This is how my code looks:

$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 outcome is a returning error. Undefined attribute: Illuminate\Database\Eloquent\Collection::$sku

So, using this code, I try to improvise a little:

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 the 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