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,

1

7 Answers 7

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

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

Hey! Thank you for taking the time and answering the question! Can you write more than your code and explain why it works?
4

You could try this,

$data = array_merge($candidate, compact('purchaseOrderNumber'));

Comments

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.

Comments

3
 $data = array_merge(['item'=>$item->toArray()], ['chef' => $chef->toArray()]);

1 Comment

While this might solve the problem, it is better to provide some explanation of what you are doing.
1
$data = $firstArray->merge($secondArray);

1 Comment

merge method is part of the Illuminate\Support\Collection class. So, to use it $firstArray must be a collection
0

Try this:

$data = [];

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

 array_merge($data,$purchaseOrderNumber);

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

 dd($data);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.