简体   繁体   English

使用Laravel检查数据库中是否已存在该值

[英]Check if the value already exists in the database using Laravel

Description: I have a site. 说明:我有一个网站。 I just want to keep track of a suspicious request and possible barn them only if needed. 我只是想跟踪一个可疑的请求,并且只在需要时才可能将它们谷仓。 I just started to implement that feature. 我刚刚开始实现该功能。 I have all the records of IP Addresses, but I'm not sure how to increment their visit count each time - they visit. 我有IP地址的所有记录,但我不确定如何每次增加他们的访问次数 - 他们访问。


Goal: To increment visit_count attribute each time user visit a site 目标:每次用户访问网站时增加visit_count属性


In my visitors table, I have an ip attribute I want to check for an existing first before, I perform the saving, and other logics, but I'm just a little stuck here. 在我的visitors表中,我有一个ip属性,我想先查看现有的,我执行保存和其他逻辑,但我只是有点卡在这里。

How do I check if the value already exists in the database using Laravel ? 如何使用Laravel检查数据库中是否已存在该值?

Any hints on this will be much appreciated ! 任何关于此的提示将非常感谢!


I've tried 我试过了

Model : Visitor.php 型号: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);
    }

}

Controller : Visitor.php 控制器: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();

}

Result 结果

I keep getting 我一直在

Argument 1 passed to Illuminate\\Validation\\Factory::make() must be of the type array, string given 传递给Illuminate \\ Validation \\ Factory :: make()的参数1必须是给定的字符串数组

I believe, it from this line here $validator = Visitor::validator($ip); 我相信,它来自这一行$validator = Visitor::validator($ip);

The error message kind of gives it away. 错误消息类型给它。 The Validator expects the values and the rules to be two separate arrays, each with keys denoting the columns name that needs to be validated. Validator期望值和规则是两个独立的数组,每个数组都带有表示需要验证的列名的键。 You have that for the rules, but not for the values being checked. 你有规则,但不是被检查的值。 This will fix your error: 这将解决您的错误:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM