Deprecate singleOrFail() in favour of sole()

This commit is contained in:
2024-11-08 23:31:21 +11:00
parent f0f2d74a14
commit 72ad1307c5
18 changed files with 27 additions and 43 deletions

View File

@@ -1,31 +1,17 @@
<?php
/**
* Add eloquent queries single(), singleOrFail(), singleOrNew()
* Add eloquent queries single(), singleOrNew()
*/
namespace App\Traits;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\ModelNotFoundException;
trait SingleOrFail
trait Single
{
private static function bootSingleOrFail(): void
private static function bootSingle(): void
{
// When a query should return 1 object, or FAIL if it doesnt
// @deprecated use sole()
Builder::macro('singleOrFail',function () {
$result = $this->get();
if (($x=$result->count()) === 1)
return $result->first();
if ($x === 0)
throw new ModelNotFoundException('Query brings back 0 record(s) called for singleOrFail()');
else
throw new \Exception(sprintf('Query brings back %d record(s) called for singleOrFail()',$x));
});
// When a query should return 1 object, or NULL if it doesnt
Builder::macro('single',function () {
$result = $this->get();