Check if value exists in database using Laravel

Description: I have a website. I just want to track a suspicious request and, possibly, plant them only if necessary. I just started to implement this function. I have all the records of IP addresses, but I'm not sure how to increase their number of visits each time - they visit.


Purpose: To increase the attribute visit_countevery time a user visits the site


In my table visitors, I have an attribute. ip I want to check the existing one, I am saving and other logics, but I'm just a little stuck here.

How to check if a value exists in a database using Laravel?

Any hints of it would be much appreciated!


I tried

Model: Visitor.php

class Visitor extends Model {

    protected $table = 'visitors';


    //Validation Rules and Validator Function
    public static function validator($input, $id = ''){

        $rules = array(

            'ip'    =>'unique:visitors,ip,'.$id,

            );

        return Validator::make($input,$rules);
    }

}

: Visitor.php

// Check for existing
$validator = Visitor::validator($ip);

if ($validator->fails()) {

    $ip = Visitor::where('ip', '=', $ip)->firstOrFail();
    $id =  $ip['attributes']['id']; //<------ Not sure if this is a proper way

    if($ip){

        $visitor              = Visitor::findOrFail($id);
        $visitor->visit_count = $visitor->visit_count + 1 ;
        $visitor->save();

    }

} else {

    $visitor              = new Visitor;

        $visitor->ip             = $ip;
        $visitor->visit_count    = $visitor->visit_count + 1 ;

    $visitor->save();

}

1, Illuminate\Validation\ Factory:: make(), , ,

, $validator = Visitor::validator($ip);

+4
1

. , , , , . , . :

return Validator::make(['ip' => $input], $rules);
+2

Source: https://habr.com/ru/post/1611099/


All Articles