I have a form field to get mobile number of users:
<input class="form-control" name="mobile" data-mask="0999 999 9999" type="text" id="mobile" />
I used jasny input mask to guide users for entering data but I need to save mobile number in format 999999999 into database (Without 0 and spaces).
As I use ajax to send data to server by serialize() function, I don't want to use client side script to change entered value (I have many such form fields) unless by changing or adding a function or method to jasny input mask to use on all such fields!
I get the entered value server-side and I want to assign it to a model attribute in Laravel 5 so in user model I declared an accessor and a mutator to set and get mobile number:
public function setMobileAttribute($value){
$value = substr(str_replace(" ","",$value),1);
$this->attributes['mobile'] = $value;
}
and
public function getMobileAttribute($value){
return '0'.substr($value,0,3).' '.substr($value,3,3).' '.substr($value,6,4);
}
It works nice but when I want to use Laravel validation to indicate it's a unique field, it doesn't work. Peace of code is like:
class UserController extends Controller {
protected $rules = ['mobile' => 'required|unique:users'];
public function store(Request $request){
$validator = Validator::make($request->all(), $this->rules);
if ($validator->fails()){
return response()->json([
'success' => false,
'errors' => $validator->getMessageBag()->toArray()
]);
}
// codes to store user...
}
}
It cause to error: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry