Search code examples
phplaravellaravel-4php-5.3php-5.4

Insert unique ipaddress in database


I have a problem. I want to insert ipaddress and date of visit of each visitors in my database but the ip is inserted every time when I refresh the page or I open a news. My code: NewsController:

public function __construct(){
     $this->beforeFilter('csrf', array('on'=>'post'));
     $sIpAddress = Visitors_lib::getIp();
     $dDateVisit = time("Y/m/d H:i:s");
     $oVisitor = new \Visitors();
     $bInsert = $oVisitor->addVisitor($sIpAddress,$dDateVisit);
}

VisitorsModel:

public function addVisitor($sIpAdress,$dDate){
    $oVisitor = new Visitors();
    $oVisitor->ipaddress = $sIpAdress;
    $oVisitor->date = $dDate;
    $oVisitor->save();
}

So I want to insert the ip only one. In this situations when I click on the news the ip is inserted in the database, so for an visitor 1 click = 1 insert.


Solution

  • Check if it already exists before entering it:

    public function addVisitor($ipaddresse, $date)
    {
        if ( ! $this->where(compact('ipaddresse'))->first())
        {
            static::create(compact('ipaddresse', 'date'));
        }
    }