Deprecate singleOrFail() in favour of sole()
This commit is contained in:
35
app/Traits/Single.php
Normal file
35
app/Traits/Single.php
Normal file
@@ -0,0 +1,35 @@
|
||||
<?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();
|
||||
|
||||
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();
|
||||
|
||||
if ($result->count() === 1)
|
||||
return $result->first();
|
||||
|
||||
return $this->newModelInstance($args);
|
||||
});
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user