clrghouz/app/Traits/Single.php

35 lines
731 B
PHP
Raw Normal View History

<?php
/**
* Add eloquent queries single(), singleOrNew()
*/
namespace App\Traits;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\ModelNotFoundException;
trait Single
{
private static function bootSingle(): void
{
// 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
}