2

我无法检查以下集合是否包含数据

$users = \App\Tempuser::where('mobile','=',$request->mobile)->get();

if(isset($users))
  return "ok";
else
  return "failed";

但如果仍然没有任何东西,$users我就没有得到其他部分。

4

4 回答 4

4

要检查集合是否为空,您可以使用以下isEmpty方法:

if( $users->isEmpty() )
  return "collection is empty";
else
  return "collection is not empty";
于 2016-10-13T16:07:19.387 回答
3

使用类似的东西if ($users->count())or if (count($users))

于 2016-10-13T16:04:07.173 回答
2

->get()将始终返回一个集合,您只需要验证它是否包含元素。

if ($users->count())
    return "ok";
else
    return "failed";
于 2016-10-13T16:04:05.200 回答
0

您可以创建一个宏并将其放入您的 AppServiceProvider

Collection::macro('assertContains', function($value) {
    Assert::assertTrue(
         $this->contains($value)
    );
});

Collection::macro('assertNotContains', function($value) {
    Assert::assertFalse(
        $this->contains($value)
    );
});
于 2017-07-18T21:01:07.043 回答