Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5 Merge an array

I am trying to merge an array with an input from a form of a random string of numbers

In my form I have

<input type="text" name="purchase_order_number" id="purchase_order_number" value="{{ $purchase_order_number }}" />

And in the controller:

public function store(CandidateRequest $request)
{
    $candidateInput = Input::get('candidates');
    $purchaseOrderNumber = Input::get('purchase_order_number');

    foreach ($candidateInput as $candidate)
    {

        $data = array_merge($candidate, [$purchaseOrderNumber]);

        $candidate = Candidate::create($data);

        dd($data);

When I dd($data) it’s getting my purchase_order_number but as seen below but how can I assign it to that row in the table?

array:6 [▼
  "candidate_number" => "5645"
  "givennames" => "fgfgf"
  "familyname" => "dfgfg"
  "dob" => "01/01/2015"
  "uln" => "45565445"
  0 => "5874587"
]

Many thanks,

like image 954
0w3n86 Avatar asked Nov 25 '15 13:11

0w3n86


People also ask

How to use array merge in Laravel?

To make this happen in Laravel, we first have to extract that array into a variable. Then, we can manipulate the data of that array variable. And finally, we merge the manipulated array variable back into the request object. Now we can access array data like $user_array['name'] or $user_array['surname'] .

How do you merge arrays?

To merge elements from one array to another, we must first iterate(loop) through all the array elements. In the loop, we will retrieve each element from an array and insert(using the array push() method) to another array. Now, we can call the merge() function and pass two arrays as the arguments for merging.

How can I merge two arrays in PHP without duplicates?

How can I merge two arrays in PHP without duplicates? You can use the PHP array_unique() function and PHP array_merge() function together to merge two arrays into one array without duplicate values in PHP.


2 Answers

I figured this out with some help but the answer is to add:

$data = array_merge($candidate, ['purchase_order_number' => $purchaseOrderNumber]);

Thanks to everyone else who tried to help :)

like image 115
0w3n86 Avatar answered Sep 30 '22 18:09

0w3n86


try this:

use Illuminate\Support\Arr;
$array = Arr::collapse([[1, 2, 3], [4, 5, 6], [7, 8, 9]]);
// [1, 2, 3, 4, 5, 6, 7, 8, 9]

more: laravel helpers

like image 21
Hossien Salamhe Avatar answered Sep 30 '22 16:09

Hossien Salamhe