【问题标题】:Eloquent condition not detecting accented letters in where conditionEloquent 条件在 where 条件下未检测到重音字母
【发布时间】:2019-05-27 07:45:54
【问题描述】:

在我的 Web 应用程序中,我有位置,每个位置都有 company_id,我不想在同一家公司有相同的位置名称。所以我做了这个:

$name = $request->get('name');
$location = Location::find($id);
if ($location->name != $name) {
    $old_location = Location::where('company_id', $location->company_id)
        ->where('name', $name)
        ->first();
    if ($old_location) {
        $errors = ['name' => trans('asset.location').' '.$name.' 
        '.trans('message.already_exists')];
            return back()->withErrors($errors)->withInput();
    }
}

问题是,如果我有Service 位置并想将其名称更改为Šervice,它不会让我这样做。我没有这样命名的位置。如果条件通过但在雄辩的搜索中失败。这怎么可能?

【问题讨论】:

    标签: laravel


    【解决方案1】:

    确保您在配置文件中正确指定了字符集。喜欢

    'charset'   => 'utf8',
    'collation' => 'utf8_unicode_ci',
    

    src:Laravel 5.1 utf-8 saving to database

    我认为,你必须在这里使用 laravel 验证。所以它可以在处理之前验证请求。

    Validator::extend('uniqueLocationInCompany', function ($attribute, $value, $parameters, $validator) {
        $count = DB::table('locations')->where('name', $value)
                                    ->where('company_id', $parameters[0])
                                    ->count();
    
        return $count === 0;
    });
    

    然后您可以在验证器函数中访问这个新规则:

    'name' => "uniqueLocationInCompany:{$request->company_id}"
    

    要更多地了解我们应该如何在 laravel 中实现验证,您应该按照此处的文档进行操作。

    https://laravel.com/docs/5.8/validation

    【讨论】:

    • charset 就是这样,问题在整理中,我提供了答案。我可以在哪里放置 Validatior::extend 代码?在什么文件中?
    • 在 App\Providers\AppServiceProvider > boot()
    • @Nemanja 如果您认为这有助于解决您的问题,请标记此内容。
    • 我刚做了,真的帮我找到了解决办法!
    【解决方案2】:

    我找到了solution!在阅读了最佳答案后,我将$old_location 的代码更改为:

    $old_location = Location::where('company_id', $location->company_id)
        ->whereRaw('name COLLATE utf8mb4_bin', $name)
        ->first();
    

    我为我的 eloquent where 条件使用了不同的排序规则,并且它完美地工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-21
      • 1970-01-01
      • 2021-07-12
      • 2015-02-25
      • 1970-01-01
      • 1970-01-01
      • 2014-07-21
      相关资源
      最近更新 更多