如果没有数据,如何抛出异常Laravel?

时间:2019-03-31 10:27:36

标签: laravel laravel-5

当我期望某些值时,如果没有数据Laravel,如何引发异常?

$roles = Auth::user()->roles()->get();

因此,使用它是一个好主意吗?

if ($roles->count() == 0) {
   throw new \Exception('No data');
}

但是如果$roles为空怎么办?

1 个答案:

答案 0 :(得分:1)

您可以使用类似的东西

$roles = Auth::user()->roles();

if($roles->isNotEmpty()){
    $roles = $roles->get();
}

参考:https://laravel.com/docs/5.8/collections