File tree Expand file tree Collapse file tree 2 files changed +46
-0
lines changed
src/Illuminate/Database/Eloquent/Relations Expand file tree Collapse file tree 2 files changed +46
-0
lines changed Original file line number Diff line number Diff line change 2
2
3
3
namespace Illuminate \Database \Eloquent \Relations ;
4
4
5
+ use Closure ;
5
6
use Illuminate \Contracts \Support \Arrayable ;
6
7
use Illuminate \Database \Eloquent \Builder ;
7
8
use Illuminate \Database \Eloquent \Collection ;
@@ -754,6 +755,28 @@ public function firstOrFail($columns = ['*'])
754
755
throw (new ModelNotFoundException )->setModel (get_class ($ this ->related ));
755
756
}
756
757
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
+
757
780
/**
758
781
* Get the results of the relationship.
759
782
*
Original file line number Diff line number Diff line change 2
2
3
3
namespace Illuminate \Database \Eloquent \Relations ;
4
4
5
+ use Closure ;
5
6
use Illuminate \Contracts \Support \Arrayable ;
6
7
use Illuminate \Database \Eloquent \Builder ;
7
8
use Illuminate \Database \Eloquent \Collection ;
@@ -301,6 +302,28 @@ public function firstOrFail($columns = ['*'])
301
302
throw (new ModelNotFoundException )->setModel (get_class ($ this ->related ));
302
303
}
303
304
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
+
304
327
/**
305
328
* Find a related model by its primary key.
306
329
*
You can’t perform that action at this time.
0 commit comments