Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add new element in laravel collection object

I want to add new element in $items array, I don't want to use joins for certain reasons.

$items = DB::select(DB::raw('SELECT * FROM items WHERE items.id = '.$id.'  ;'));         foreach($items as $item){             $product = DB::select(DB::raw(' select * from product                    where product_id = '. $id.';' ));              $item->push($product);         } 

What should I do?

like image 909
Talib Hussain Avatar asked Nov 20 '15 14:11

Talib Hussain


People also ask

How do you add value to a collection?

Java Collection add() methodThe add() method of Java Collection Interface inserts the specified element in this Collection. It returns a Boolean value 'true', if it succeeds to insert the element in the specified collection else it returns 'false'.

What does get () do in laravel?

This allows you to add conditions throughout your code until you actually want to fetch them, and then you would call the get() function.

What is pluck in laravel?

Laravel Pluck() is a Laravel Collections method used to extract certain values from the collection. You might often would want to extract certain data from the collection i.e Eloquent collection.

Is a collection an object in laravel?

Collections are basically an extension to the php native array. It's meant to work with arrays. The arrays can certainly contain objects, such as eloquent results, but at the core it's an array.


2 Answers

It looks like you have everything correct according to Laravel docs, but you have a typo

$item->push($product); 

Should be

$items->push($product); 

push method appends an item to the end of the collection:

I also want to think the actual method you're looking for is put

$items->put('products', $product); 

put method sets the given key and value in the collection

like image 163
Pastor Bones Avatar answered Oct 13 '22 06:10

Pastor Bones


As mentioned above if you wish to add as a new element your queried collection you can use:

    $items = DB::select(DB::raw('SELECT * FROM items WHERE items.id = '.$id.'  ;'));     foreach($items as $item){         $product = DB::select(DB::raw(' select * from product                where product_id = '. $id.';' ));          $items->push($product);         // or          // $items->put('products', $product);     } 

but if you wish to add new element to each queried element you need to do like:

    $items = DB::select(DB::raw('SELECT * FROM items WHERE items.id = '.$id.'  ;'));     foreach($items as $item){            $product = DB::select(DB::raw(' select * from product                  where product_id = '. $id.';' ));                $item->add_whatever_element_you_want = $product;     } 

add_whatever_element_you_want can be whatever you wish that your element is named (like product for example).

like image 22
Alpy Avatar answered Oct 13 '22 04:10

Alpy