First of all it is necessary to clarify to the future visitors of this question that isset()
is not a function or helper of Laravel, it is a native function of PHP and exists since PHP 4.x
This function is used to determine if a variable is defined (or not) and if its value is not NULL.
When using Eloquent and its method get()
, when there are no results we get something like this:
Collection {#705 ▼
#items: []
}
As you can see, it is an empty collection, but the variable is defined and its value is not NULL, so a check with isset()
will throw true .
If the idea is to deliver a false or similar when checking whether the result of a query is empty or not, findOrFail()
is not the solution either, since this function throws an exception in case a model is not found for its primary key. I leave as a reference your source code:
/**
* Find a model by its primary key or throw an exception.
*
* @param mixed $id
* @param array $columns
* @return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Collection
*
* @throws \Illuminate\Database\Eloquent\ModelNotFoundException
*/
public function findOrFail($id, $columns = ['*'])
{
$result = $this->find($id, $columns);
if (is_array($id)) {
if (count($result) == count(array_unique($id))) {
return $result;
}
} elseif (! is_null($result)) {
return $result;
}
throw (new ModelNotFoundException)->setModel(
get_class($this->model), $id
);
}
In this case the best solution is to use the isNotEmpty()
method of collections in Eloquent, which will deliver true
if the collection is not empty, and false
if it is empty.
$usuarios = usuarios::whereUsuarioAd('danielad')->get();
if ($usuarios->isNotEmpty()) {
// colección no está vacía
} else {
// colección vacía
}
Finally, in the code that I see in the response that the same OP raises, the rules of PSR-2, the official style guide of PHP and Laravel, are NOT being followed. Please carefully review the following link: link