46 lines
1.1 KiB
PHP
46 lines
1.1 KiB
PHP
<?php
|
|
|
|
/**
|
|
* Extend Eloquent so that it includes singleOrFail calls to test that a query returns only 1 record
|
|
*/
|
|
namespace App\Traits;
|
|
|
|
use Illuminate\Database\Eloquent\Builder;
|
|
use Illuminate\Database\Eloquent\ModelNotFoundException;
|
|
|
|
trait SingleOrFail
|
|
{
|
|
public static function bootSingleOrfail(): void
|
|
{
|
|
// When a query should return 1 object, or FAIL if it doesnt
|
|
Builder::macro('singleOrFail',function () {
|
|
$result = $this->get();
|
|
|
|
if (($x=$result->count()) == 1)
|
|
return $result->first();
|
|
|
|
throw new ModelNotFoundException(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();
|
|
|
|
if ($result->count() == 1)
|
|
return $result->first();
|
|
|
|
return NULL;
|
|
});
|
|
|
|
// When a query should return 1 object, or setup to create a new object
|
|
Builder::macro('singleOrNew',function (array $args=[]) {
|
|
$result = $this->where($args)->get();
|
|
|
|
if ($result->count() == 1)
|
|
return $result->first();
|
|
|
|
return $this->newModelInstance($args);
|
|
});
|
|
}
|
|
}
|