Skip to content
Advertisement

Passing a variable to a ->each() function making the variable always = 0 php

One of the routes I’m making for my API in laravel requires me to pass a variable to a ->each() function.

This can be seen below:

public function by_location($zone_id)
{
    $zone = Zone::where('id', $zone_id)->get()[0];
    error_log($zone->id);
    $exhibitors = Exhibitor::where('zone_id', $zone_id)->get();
    $exhibitors->each(function($exhibitor, $zone)
    {
        error_log($zone->id);
        $exhibitor['zone_info'] = $zone;
    });
    return response()->json($exhibitors);
}

This first error_log outputs ‘2’, but with the second I get ‘Trying to get property ‘id’ of non-object’.

Any help is apprecited!

Advertisement

Answer

You probably want to use $zone which you selected from database on first line. Also if you want to change value of item you are iterating you have to use ->map() instead of ->each()

I changed ->get()[0] to ->first(). Never use ->get()[0]

public function by_location($zone_id)
{
    $zone = Zone::where('id', $zone_id)->first();
    error_log($zone->id);
    $exhibitors = Exhibitor::where('zone_id', $zone_id)->get();
    $exhibitors->map(function($exhibitor) use ($zone){
        error_log($zone->id);
        $exhibitor['zone_info'] = $zone;
        return $exhibitor;
    });

    return response()->json($exhibitors);
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement