diff --git a/src/Traits/SingleOrFail.php b/src/Traits/SingleOrFail.php new file mode 100644 index 0000000..6df7f0d --- /dev/null +++ b/src/Traits/SingleOrFail.php @@ -0,0 +1,45 @@ +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 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); + }); + } +} \ No newline at end of file