PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, March 16, 2022

[FIXED] Concatenate two inputs in a single Database row

 March 16, 2022     laravel, php     No comments   

Issue

I want to add a country phone number prefix based on the country chosen. I want it saved with the phone number as the same column on the database. The best option would be to add another column for prefix (countryCode in my case) but I want them concatenated together. Since I lack some experience when it comes to PHP I'm struggling a bit. This is my HTML. Any suggestions or instructions?

<div>
  <label for="countryCode" value="Country Code"/>
  <select name="countryCode">
  <option>Denmark (+45)</option>
  <option>Mauritius (+230)</option>
  </select>
</div>
<div>
  <label for="phone" value="Phone"/>
  <input type="number" name="phone"/>
</div>

This is my migrations table

$table->string('phone')->nullable();

This is my fortify file:

Validator::make($input,['phone' => ['required', 'string'],])->validate();
$company = Model::firstOrCreate([]],['phone' => $input['phone'],]);

This is my model:

protected $fillable = [
        'phone',
    ];

This is part of a two step authentication. This is the first step. I removed most of the unnecessary code.


Solution

In order to make your code work, first in your html for the country selectors, add value so you can access them in the controller

<div>
  <label for="countryCode" value="Country Code"/>
  <select name="countryCode">
  <option value="+45">Denmark (+45)</option>
  <option value="+230">Mauritius (+230)</option>
  </select>
</div>
<div>
  <label for="phone" value="Phone"/>
  <input type="number" name="phone"/>
</div>

After that you should validate both input field in the controller:

Validator::make($input,['phone'       => ['required', 'string'],
                        'countryCode' => ['required', 'string'] 
                ])->validate();

And finally in the controller you can concatenate the two input and store it in one field with the . operator:

$company = Model::firstOrCreate([]],['phone' => $input['countryCode'].$input['phone'],]);

If the above code does not work (I just copied it from the question) try this instead:

$company = Model::create(['phone' => $input['countryCode'].$input['phone']]);


Answered By - Mátyás GrÅ‘ger
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing