Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

artisticre's avatar

Phone Number Format

I have this function that shows the users phone number but I am not sure how to format it as (xxx) 555-1212. Any help would be appreciated.

 $admin_applist = DB::table('employmentapplication')
    ->select('id','Fname', 'Lname', 'phone', 'email')
         ->get();
         
          return view('/admin')->with(compact('admin_applist'));

0 likes
9 replies
Tray2's avatar

Something like this should work.

In your model.

function getPhoneNumberAttribute()
{
    $cleaned = preg_replace('/[^[:digit:]]/', '', $this->phone);
    preg_match('/(\d{3})(\d{3})(\d{4})/', $cleaned, $matches);
    return "({$matches[1]}) {$matches[2]}-{$matches[3]}";
}

Then you can call it

{{ $admin_applist->phoneNumber }}
2 likes
Cronix's avatar
$phone = "1234567890";

$ac = substr($phone, 0, 3); // 123
$prefix = substr($phone, 3, 3); // 456
$suffix = substr($phone, 6); // 7890

$formatted = "({$ac}) {$prefix}-{$suffix}";

Make an accessor

public function getPhoneFormattedAttribute() {
    $phone = $this->phone;

    $ac = substr($phone, 0, 3);
    $prefix = substr($phone, 3, 3);
    $suffix = substr($phone, 6);

    return "({$ac}) {$prefix}-{$suffix}";
}
$admin_applist = DB::table('employmentapplication')
    ->select('id','Fname', 'Lname', 'phone', 'email')
         ->get();

echo $admin_applist->phone_formatted;
2 likes
cmdobueno's avatar

This is why I always try to suggest that people use models, i understand the easy of use of DB, but here is my example...

Your Code Converted:

$admin_applist = EmploymentApplication::get(['id','Fname', 'Lname', 'phone', 'email']);
return view('/admin')->with(compact('admin_applist'));

EmploymentApplication Class

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class EmploymentApplication extends Model {

    public function getPhoneAttribute(){

        $phone = preg_replace("/[^0-9]/","",$this->phone); //Remove all non-numers

        
        return substr($phone ,2,3)."-".substr($phone ,6,3)."-".substr($phone ,10,4);
    }

    //I ALSO SUGGEST CLEANING THE NUMBER WHEN ADDING TO THE DB
    public function setPhoneAttribute($value){
        $this->attributes['phone'] = preg_replace("/[^0-9]/","",$value);
    }
}


This would be my method, the getPhoneAttribute will modify it when it is sent to the view, so you will always be dealing with a nice clean phone number

I do the set, just to clean my data a bit in my database... no other reason.
artisticre's avatar

OK I did the following and get Trying to get property of non-object

 public function getPhoneFormattedAttribute() {
      $phone = $this->phone;
  
      $ac = substr($phone, 0, 3);
      $prefix = substr($phone, 3, 3);
      $suffix = substr($phone, 6);
  
      return "({$ac}) {$prefix}-{$suffix}";
  }

    public function index()
    {
     $admin_applist = DB::table('employmentapplication')
    ->select('id','Fname', 'Lname', 'phone', 'email')
    ->get();
     return view('/admin')->with(compact('admin_applist'->phone_formatted));
    }
cmdobueno's avatar

You must use a model as I said.

You are using DB... if you decide you want to continue to use DB instead of a model you have to do something like this...


private function formatPhoneNumber($phone) {
     
      $ac = substr($phone, 0, 3);
      $prefix = substr($phone, 3, 3);
      $suffix = substr($phone, 6);
  
      return "({$ac}) {$prefix}-{$suffix}";
  }

public function index()
    {
     $admin_applist = DB::table('employmentapplication')
    ->select('id','Fname', 'Lname', 'phone', 'email')
    ->get();

    foreach($admin_applist as $item){
        $item->phone = $this->formatPhoneNumber($item->phone);
    }
    

     return view('/admin')->with(compact('admin_applist'));
    }

But again, this is why laravel has models. This is a perfect example of where a model should be used. It needs to be used. You want to modify every single items phone number, and the model will do it for you.

Just read the examples you have been given, dont just take a function and be like... its cool it will work. There are explainations and people have spent time to go as far as explain it... each perosn has explained how to solve this, the three different people all have basically the exact same solution for you. USE A MODEL, and then USE A MUTATOR.

construct's avatar

I do agree with the rest of the post above, however if its of importance I use stuff like..

https://numverify.com/

https://www.twilio.com/lookup

it isn't answering your question since others have already done it, but I think its worth knowing that these will return a fully validated formatted number for you. Anyways, just though I would share a suggestion.

jlrdw's avatar

substr and other php string functions, it would have been nice if you were already well endowed it that sort of thing prior to laravel. Laravel is a php framework. Therefore the laravel way is the php way. Just an observation. Taylor made may helpers (shortcuts) to assist, but behind them are normal php functions making laravel do it's thing.

artisticre's avatar

So I guess I don't understand Models. I did the following as stated and I get Base table or view not found: 1146 Table 'tlcofficial.clean_phones' doesn't exist (SQL: select id, Fname, Lname, phone, email from clean_phones)

  public function index()
    {
      $admin_applist = CleanPhone::get(['id','Fname', 'Lname', 'phone', 'email']);
      return view('/admin')->with(compact('admin_applist'));
    }


<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class CleanPhone extends Model
{
      public function getPhoneAttribute(){
        $phone = preg_replace("/[^0-9]/","",$this->phone); //Remove all non-numers
           return substr($phone ,2,3)."-".substr($phone ,6,3)."-".substr($phone ,10,4);
        }
    
        //I ALSO SUGGEST CLEANING THE NUMBER WHEN ADDING TO THE DB
        public function setPhoneAttribute($value){
            $this->attributes['phone'] = preg_replace("/[^0-9]/","",$value);
        }
    }
    


jlrdw's avatar

I would consider setting up a practice database, and actually do the examples in the docs, and perhaps vieu a few more videos. Are you aware that there is examples and code on github to practice with.

Please or to participate in this conversation.