使用 laravel 的 eloquent 命令,数据库查询未按预期工作

Database Query not working as expected using eloquent commands for laravel

我正在尝试查询连接到我的模型 "Address" 的数据库,以查找 'LIKE' 在地址输入字段中输入到我的表单中的任何地址。我的模型代码是:

public function CheckForPrevious($verify)

{
  $matches = \App\Address::where('address', 'like', '%'.$verify.'%')

  ->get();

  foreach($matches as $match)
  {
    echo "$match";
  }



}

我的控制器代码是:

public function show()
    {
      $address = new Address;
      $check = $_POST['address'];

      $address->CheckForPrevious($check);

      return $address;

    }

如有任何帮助,我们将不胜感激

您不必为查询范围函数添加前缀 scope

改变

  `$address->scopeCheckForPrevious($check)`

  `$address->CheckForPrevious($check)`
public function show()
{
  $address = new Address();
  $check = $_POST['address'];

  $address->scopeCheckForPrevious($check);

}

public 函数 scopeCheckForPrevious($verify)

    {
      $query = App\Address::where('address', 'like', '%'.$verify.'%')

      ->get();

      foreach($query as $match)
      {
        echo "$match";
      }



    }

使用这个

不需要访问范围内不必要的模型
$query = App\Address::where('address', 'like', '%'.$verify.'%')

这样试试:

public function scopeCheckForPrevious($query, $verify)
{
    return $query->where('address', 'like', '%'.$verify.'%');
}

并使用以下代码调用它:

$address = new Address;
$check = $_POST['address'];
dd( $address->checkForPrevious($check)->get() );