8

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,

0w3n86
  • 519
  • 2
  • 4
  • 14

7 Answers7

21

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 :)

0w3n86
  • 519
  • 2
  • 4
  • 14
11

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

Hossien Salamhe
  • 111
  • 2
  • 8
  • Hey! Thank you for taking the time and answering the question! Can you write more than your code and explain why it works? – Max Oct 13 '20 at 20:53
4

You could try this,

$data = array_merge($candidate, compact('purchaseOrderNumber'));
Pantelis Peslis
  • 14,930
  • 5
  • 44
  • 45
3

Another way to do this (the simplest I think) is to do a union of arrays

$candidate += ['purchase_order_number' => $purchaseOrderNumber]; 

The + operator returns the right-hand array appended to the left-hand array; for keys that exist in both arrays, the elements from the left-hand array will be used, and the matching elements from the right-hand array will be ignored.

Dexter Bengil
  • 5,995
  • 6
  • 35
  • 54
3
 $data = array_merge(['item'=>$item->toArray()], ['chef' => $chef->toArray()]);
1
$data = $firstArray->merge($secondArray);
Mohsin Raza
  • 488
  • 1
  • 6
  • 12
  • 2
    `merge` method is part of the `Illuminate\Support\Collection` class. So, to use it `$firstArray` must be a [collection](https://laravel.com/docs/9.x/collections#method-merge) – Wesley Gonçalves May 05 '22 at 21:11
0

Try this:

$data = [];

foreach ($candidateInput as $candidate)
    array_push($data,$candidate);

 array_merge($data,$purchaseOrderNumber);

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

 dd($data);
sschuberth
  • 28,386
  • 6
  • 101
  • 146
Houssain Amrani
  • 329
  • 2
  • 6