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.
CodePudding user response:
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']]);