2021-07-16 06:55:26 +00:00
|
|
|
<?php
|
|
|
|
|
|
|
|
/**
|
2024-11-08 12:31:21 +00:00
|
|
|
* Add eloquent queries single(), singleOrNew()
|
2021-07-16 06:55:26 +00:00
|
|
|
*/
|
|
|
|
namespace App\Traits;
|
|
|
|
|
|
|
|
use Illuminate\Database\Eloquent\Builder;
|
|
|
|
use Illuminate\Database\Eloquent\ModelNotFoundException;
|
|
|
|
|
2024-11-08 12:31:21 +00:00
|
|
|
trait Single
|
2021-07-16 06:55:26 +00:00
|
|
|
{
|
2024-11-08 12:31:21 +00:00
|
|
|
private static function bootSingle(): void
|
2021-07-16 06:55:26 +00:00
|
|
|
{
|
|
|
|
// 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)
|
2021-07-16 06:55:26 +00:00
|
|
|
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)
|
2021-07-16 06:55:26 +00:00
|
|
|
return $result->first();
|
|
|
|
|
|
|
|
return $this->newModelInstance($args);
|
|
|
|
});
|
|
|
|
}
|
2023-06-27 07:39:11 +00:00
|
|
|
}
|