8000 Add firstOr methods to relationship classes (#38694) · laravel/framework@75969f7 · GitHub
[go: up one dir, main page]

Skip to content

Commit 75969f7

Browse files
authored
Add firstOr methods to relationship classes (#38694)
1 parent 01b7c08 commit 75969f7

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
namespace Illuminate\Database\Eloquent\Relations;
44

5+
use Closure;
56
use Illuminate\Contracts\Support\Arrayable;
67
use Illuminate\Database\Eloquent\Builder;
78
use Illuminate\Database\Eloquent\Collection;
@@ -754,6 +755,28 @@ public function firstOrFail($columns = ['*'])
754755
throw (new ModelNotFoundException)->setModel(get_class($this->related));
755756
}
756757

758+
/**
759+
* Execute the query and get the first result or call a callback.
760+
*
761+
* @param \Closure|array $columns
762+
* @param \Closure|null $callback
763+
* @return \Illuminate\Database\Eloquent\Model|static|mixed
764+
*/
765+
public function firstOr($columns = ['*'], Closure $callback = null)
766+
{
767+
if ($columns instanceof Closure) {
768+
$callback = $columns;
769+
770+
$columns = ['*'];
771+
}
772+
773+
if (! is_null($model = $this->first($columns))) {
774+
return $model;
775+
}
776+
777+
return $callback();
778+
}
779+
757780
/**
758781
* Get the results of the relationship.
759782
*

src/Illuminate/Database/Eloquent/Relations/HasManyThrough.php

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
namespace Illuminate\Database\Eloquent\Relations;
44

5+
use Closure;
56
use Illuminate\Contracts\Support\Arrayable;
67
use Illuminate\Database\Eloquent\Builder;
78
use Illuminate\Database\Eloquent\Collection;
@@ -301,6 +302,28 @@ public function firstOrFail($columns = ['*'])
301302
throw (new ModelNotFoundException)->setModel(get_class($this->related));
302303
}
303304

305+
/**
306+
* Execute the query and get the first result or call a callback.
307+
*
308+
* @param \Closure|array $columns
309+
* @param \Closure|null $callback
310+
* @return \Illuminate\Database\Eloquent\Model|static|mixed
311+
*/
312+
public function firstOr($columns = ['*'], Closure $callback = null)
313+
{
314+
if ($columns instanceof Closure) {
315+
$callback = $columns;
316+
317+
$columns = ['*'];
318+
}
319+
320+
if (! is_null($model = $this->first($columns))) {
321+
return $model;
322+
}
323+
324+
return $callback();
325+
}
326+
304327
/**
305328
* Find a related model by its primary key.
306329
*

0 commit comments

Comments
 (0)
0