a.hamza
a.hamza

Reputation: 35

Format phone number in Laravel Blade

Is there a simple way to format a phone string for display in a Laravel Blade template?

I am trying to take '612345678'

and insert it as {{ $user{'phone'] }} and have it display as 612 345 678

Upvotes: 3

Views: 16580

Answers (4)

Lance
Lance

Reputation: 21

This will give you (###) ###-####

preg_replace('~.*(\d{3})[^\d]{0,7}(\d{3})[^\d]{0,7}(\d{4}).*~', '($1) $2-$3', $simple->phone) 

Upvotes: 2

Shreeraj
Shreeraj

Reputation: 767

You can try this:

$format = chunk_split($user['phone'], 3, ' ');

You will get your phone number as "612 345 678 " with a space trailing behind. To remove the last space trailing behind, you can use rtrim() function.

rtrim($format, ' ');

Hope this works.

Upvotes: 1

Sujan Gainju
Sujan Gainju

Reputation: 4769

add the function in the model

public function phoneNumber() {
    // add logic to correctly format number here
    // a more robust ways would be to use a regular expression
    return "(".substr($data, 0, 3).") ".substr($data, 3, 3)." ".substr($data,6);
}

and display it into your blade as

{{ $user->phoneNumber() }}

Upvotes: 2

Unamata Sanatarai
Unamata Sanatarai

Reputation: 6647

Feel free to use the following package: https://github.com/Propaganistas/Laravel-Phone

and use it for example:

{{ phone('612345678'); }}
{{ phone($user['phone'], 'US'); }}

Upvotes: 9

Related Questions