自定义验证类

namespace App\Validators;

class DatabaseUniqueValidator
{
    public function validate($attribute, $value, $parameters, $validator)
    {
        list($db, $table) = $parameters;

        return !app('db')->connection($db)->table($table)->where($attribute, $value)->exists();
    }
}

添加自定义验证

AppServiceProvider 文件添加如下代码。

protected $validators = [
    'database_unique' => \App\Validators\DatabaseUniqueValidator::class,
];

public function boot()
{
    foreach ($this->validators as $rule => $validator) {
        app('validator')->extend($rule, "{$validator}@validate");
    }
}

使用

database_unique 后第一个参数是数据库链接,第二个是表。

$this->validate($request, [
    'url' => 'required|active_url|database_unique:mysql_article,articles',
]);

参考阅读