clrghouz/app/Traits/SingleOrFail.php

49 lines
1.2 KiB
PHP
Raw Permalink Normal View History

<?php
/**
* Add eloquent queries single(), singleOrFail(), singleOrNew()
*/
namespace App\Traits;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\ModelNotFoundException;
trait SingleOrFail
{
2021-09-28 12:27:21 +00:00
private static function bootSingleOrFail(): void
{
// When a query should return 1 object, or FAIL if it doesnt
2024-11-04 07:25:49 +00:00
// @deprecated use sole()
Builder::macro('singleOrFail',function () {
$result = $this->get();
2023-06-27 07:39:11 +00:00
if (($x=$result->count()) === 1)
return $result->first();
2023-06-27 07:39:11 +00:00
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();
2023-06-27 07:39:11 +00:00
if ($result->count() === 1)
return $result->first();
return NULL;
});
// When a query should return 1 object, or NULL if it doesnt
Builder::macro('singleOrNew',function ($args) {
$result = $this->where($args)->get();
2023-06-27 07:39:11 +00:00
if ($result->count() === 1)
return $result->first();
return $this->newModelInstance($args);
});
}
2023-06-27 07:39:11 +00:00
}