salomon022's avatar

"array_push() expects parameter 1 to be array, object given"

foreach($products as $product)
        {
            
            $refer = 'book';
            $refers = array();
            $refers['refer '] =$refer ;
            array_push($product,   $refers);
            return  $product;
    }
0 likes
4 replies
salomon022's avatar
$now = carbon::now()->toDateTimeString();

$products = DB::table('product')->where('product_start_time', '<=', $now)->where('product_expiry_time', '>', $now)->get();
adamprickett's avatar
Level 6

So the contents of the $products Collection are instances of stdClass and not arrays.

You can set directly to an stdClass by assigning an attribute:

foreach($products as $product)
{   
    $refer = 'book';
    $refers = array();
    $refers['refer'] = $refer ;
    // array_push($product, $refers);

    $product->refers = $refers;
    
    return  $product;
}

Also, are you meaning to return at the end of the foreach block? This will return the first $product object rather than iterating over each element.

1 like

Please or to participate in this conversation.