首页 > 解决方案 > 如果没有数据 Laravel 如何抛出异常?

问题描述

当我期望一些值时,如果没有数据 Laravel 如何抛出异常?

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

那么,使用:

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

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

标签: laravellaravel-5

解决方案


你可以使用这样的东西

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

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

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


推荐阅读