Search code examples
phplaraveldnsip

How to extract IP address from Spatie\Dns\Records\A object in Laravel


I'm working with Laravel and Spatie DNS Retriever to get the ip address from a domain name.

This is my Controller method:

public function getDomainInfo($domain)
    {
        $dns = new Dns();
        $recordsA = $dns->getRecords($domain, ['A', 'CNAME']);

        // dd($recordsA);

        $ip = $recordsA[0]->ip;
        dd($ip);

        return view('client.domain', compact('records','recordsA','recordsMX','recordsMX','recordsAll'));
    }

And I get this error:

Cannot access protected property Spatie\Dns\Records\A::$ip

However results of dd($recordsA) shows this as output:

array:1 [▼ // app/Http/Controllers/Client/IpInfoController.php:43
  0 => Spatie\Dns\Records\A {#294 ▼
    #host: "google.com"
    #ttl: 418
    #class: "IN"
    #type: "A"
    #ip: "216.239.38.120"
  }
]

So what's going wrong here? How can get the ip value in this case?

I also tried getting the ip value like this but didn't work out:

dd($recordsA[0]['ip']);

And returns this error:

Cannot use object of type Spatie\Dns\Records\A as array


Solution

  • array:1 [▼ // app/Http/Controllers/Client/IpInfoController.php:43
      0 => Spatie\Dns\Records\A {#294 ▼
        #host: "google.com"
        #ttl: 418
        #class: "IN"
        #type: "A"
        #ip: "216.239.38.120"
      }
    ]
    

    You can get this by calling as a function for example:

    public function getDomainInfo($domain)
    {
       $dns = new Dns();
       $recordsA = $dns->getRecords($domain, ['A', 'CNAME']);
       
       $ip = $recordsA[0]->ip();
       $host = $recordsA[0]->host();
       dd($ip, $host);
    
       return view('client.domain', compact('records','recordsA','recordsMX','recordsMX','recordsAll'));
    }