Subversion-Projekte lars-tiefland.laravel_shop

Revision

Revision 621 | Zur aktuellen Revision | Details | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
148 lars 1
<?php
2
 
3
namespace Illuminate\Database\Eloquent;
4
 
5
use ArrayAccess;
6
use Illuminate\Contracts\Broadcasting\HasBroadcastChannel;
7
use Illuminate\Contracts\Queue\QueueableCollection;
8
use Illuminate\Contracts\Queue\QueueableEntity;
9
use Illuminate\Contracts\Routing\UrlRoutable;
10
use Illuminate\Contracts\Support\Arrayable;
11
use Illuminate\Contracts\Support\CanBeEscapedWhenCastToString;
12
use Illuminate\Contracts\Support\Jsonable;
13
use Illuminate\Database\ConnectionResolverInterface as Resolver;
14
use Illuminate\Database\Eloquent\Collection as EloquentCollection;
15
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
16
use Illuminate\Database\Eloquent\Relations\Concerns\AsPivot;
17
use Illuminate\Database\Eloquent\Relations\HasManyThrough;
18
use Illuminate\Database\Eloquent\Relations\Pivot;
19
use Illuminate\Support\Arr;
20
use Illuminate\Support\Collection as BaseCollection;
21
use Illuminate\Support\Str;
22
use Illuminate\Support\Traits\ForwardsCalls;
23
use JsonSerializable;
24
use LogicException;
25
 
26
abstract class Model implements Arrayable, ArrayAccess, CanBeEscapedWhenCastToString, HasBroadcastChannel, Jsonable, JsonSerializable, QueueableEntity, UrlRoutable
27
{
28
    use Concerns\HasAttributes,
29
        Concerns\HasEvents,
30
        Concerns\HasGlobalScopes,
31
        Concerns\HasRelationships,
32
        Concerns\HasTimestamps,
33
        Concerns\HidesAttributes,
34
        Concerns\GuardsAttributes,
35
        ForwardsCalls;
36
 
37
    /**
38
     * The connection name for the model.
39
     *
40
     * @var string|null
41
     */
42
    protected $connection;
43
 
44
    /**
45
     * The table associated with the model.
46
     *
47
     * @var string
48
     */
49
    protected $table;
50
 
51
    /**
52
     * The primary key for the model.
53
     *
54
     * @var string
55
     */
56
    protected $primaryKey = 'id';
57
 
58
    /**
59
     * The "type" of the primary key ID.
60
     *
61
     * @var string
62
     */
63
    protected $keyType = 'int';
64
 
65
    /**
66
     * Indicates if the IDs are auto-incrementing.
67
     *
68
     * @var bool
69
     */
70
    public $incrementing = true;
71
 
72
    /**
73
     * The relations to eager load on every query.
74
     *
75
     * @var array
76
     */
77
    protected $with = [];
78
 
79
    /**
80
     * The relationship counts that should be eager loaded on every query.
81
     *
82
     * @var array
83
     */
84
    protected $withCount = [];
85
 
86
    /**
87
     * Indicates whether lazy loading will be prevented on this model.
88
     *
89
     * @var bool
90
     */
91
    public $preventsLazyLoading = false;
92
 
93
    /**
94
     * The number of models to return for pagination.
95
     *
96
     * @var int
97
     */
98
    protected $perPage = 15;
99
 
100
    /**
101
     * Indicates if the model exists.
102
     *
103
     * @var bool
104
     */
105
    public $exists = false;
106
 
107
    /**
108
     * Indicates if the model was inserted during the current request lifecycle.
109
     *
110
     * @var bool
111
     */
112
    public $wasRecentlyCreated = false;
113
 
114
    /**
115
     * Indicates that the object's string representation should be escaped when __toString is invoked.
116
     *
117
     * @var bool
118
     */
119
    protected $escapeWhenCastingToString = false;
120
 
121
    /**
122
     * The connection resolver instance.
123
     *
124
     * @var \Illuminate\Database\ConnectionResolverInterface
125
     */
126
    protected static $resolver;
127
 
128
    /**
129
     * The event dispatcher instance.
130
     *
131
     * @var \Illuminate\Contracts\Events\Dispatcher
132
     */
133
    protected static $dispatcher;
134
 
135
    /**
136
     * The array of booted models.
137
     *
138
     * @var array
139
     */
140
    protected static $booted = [];
141
 
142
    /**
143
     * The array of trait initializers that will be called on each new instance.
144
     *
145
     * @var array
146
     */
147
    protected static $traitInitializers = [];
148
 
149
    /**
150
     * The array of global scopes on the model.
151
     *
152
     * @var array
153
     */
154
    protected static $globalScopes = [];
155
 
156
    /**
157
     * The list of models classes that should not be affected with touch.
158
     *
159
     * @var array
160
     */
161
    protected static $ignoreOnTouch = [];
162
 
163
    /**
164
     * Indicates whether lazy loading should be restricted on all models.
165
     *
166
     * @var bool
167
     */
168
    protected static $modelsShouldPreventLazyLoading = false;
169
 
170
    /**
171
     * The callback that is responsible for handling lazy loading violations.
172
     *
173
     * @var callable|null
174
     */
175
    protected static $lazyLoadingViolationCallback;
176
 
177
    /**
178
     * Indicates if an exception should be thrown instead of silently discarding non-fillable attributes.
179
     *
180
     * @var bool
181
     */
182
    protected static $modelsShouldPreventSilentlyDiscardingAttributes = false;
183
 
184
    /**
185
     * The callback that is responsible for handling discarded attribute violations.
186
     *
187
     * @var callable|null
188
     */
189
    protected static $discardedAttributeViolationCallback;
190
 
191
    /**
192
     * Indicates if an exception should be thrown when trying to access a missing attribute on a retrieved model.
193
     *
194
     * @var bool
195
     */
196
    protected static $modelsShouldPreventAccessingMissingAttributes = false;
197
 
198
    /**
199
     * The callback that is responsible for handling missing attribute violations.
200
     *
201
     * @var callable|null
202
     */
203
    protected static $missingAttributeViolationCallback;
204
 
205
    /**
206
     * Indicates if broadcasting is currently enabled.
207
     *
208
     * @var bool
209
     */
210
    protected static $isBroadcasting = true;
211
 
212
    /**
213
     * The name of the "created at" column.
214
     *
215
     * @var string|null
216
     */
217
    const CREATED_AT = 'created_at';
218
 
219
    /**
220
     * The name of the "updated at" column.
221
     *
222
     * @var string|null
223
     */
224
    const UPDATED_AT = 'updated_at';
225
 
226
    /**
227
     * Create a new Eloquent model instance.
228
     *
229
     * @param  array  $attributes
230
     * @return void
231
     */
232
    public function __construct(array $attributes = [])
233
    {
234
        $this->bootIfNotBooted();
235
 
236
        $this->initializeTraits();
237
 
238
        $this->syncOriginal();
239
 
240
        $this->fill($attributes);
241
    }
242
 
243
    /**
244
     * Check if the model needs to be booted and if so, do it.
245
     *
246
     * @return void
247
     */
248
    protected function bootIfNotBooted()
249
    {
250
        if (! isset(static::$booted[static::class])) {
251
            static::$booted[static::class] = true;
252
 
253
            $this->fireModelEvent('booting', false);
254
 
255
            static::booting();
256
            static::boot();
257
            static::booted();
258
 
259
            $this->fireModelEvent('booted', false);
260
        }
261
    }
262
 
263
    /**
264
     * Perform any actions required before the model boots.
265
     *
266
     * @return void
267
     */
268
    protected static function booting()
269
    {
270
        //
271
    }
272
 
273
    /**
274
     * Bootstrap the model and its traits.
275
     *
276
     * @return void
277
     */
278
    protected static function boot()
279
    {
280
        static::bootTraits();
281
    }
282
 
283
    /**
284
     * Boot all of the bootable traits on the model.
285
     *
286
     * @return void
287
     */
288
    protected static function bootTraits()
289
    {
290
        $class = static::class;
291
 
292
        $booted = [];
293
 
294
        static::$traitInitializers[$class] = [];
295
 
296
        foreach (class_uses_recursive($class) as $trait) {
297
            $method = 'boot'.class_basename($trait);
298
 
299
            if (method_exists($class, $method) && ! in_array($method, $booted)) {
300
                forward_static_call([$class, $method]);
301
 
302
                $booted[] = $method;
303
            }
304
 
305
            if (method_exists($class, $method = 'initialize'.class_basename($trait))) {
306
                static::$traitInitializers[$class][] = $method;
307
 
308
                static::$traitInitializers[$class] = array_unique(
309
                    static::$traitInitializers[$class]
310
                );
311
            }
312
        }
313
    }
314
 
315
    /**
316
     * Initialize any initializable traits on the model.
317
     *
318
     * @return void
319
     */
320
    protected function initializeTraits()
321
    {
322
        foreach (static::$traitInitializers[static::class] as $method) {
323
            $this->{$method}();
324
        }
325
    }
326
 
327
    /**
328
     * Perform any actions required after the model boots.
329
     *
330
     * @return void
331
     */
332
    protected static function booted()
333
    {
334
        //
335
    }
336
 
337
    /**
338
     * Clear the list of booted models so they will be re-booted.
339
     *
340
     * @return void
341
     */
342
    public static function clearBootedModels()
343
    {
344
        static::$booted = [];
345
 
346
        static::$globalScopes = [];
347
    }
348
 
349
    /**
350
     * Disables relationship model touching for the current class during given callback scope.
351
     *
352
     * @param  callable  $callback
353
     * @return void
354
     */
355
    public static function withoutTouching(callable $callback)
356
    {
357
        static::withoutTouchingOn([static::class], $callback);
358
    }
359
 
360
    /**
361
     * Disables relationship model touching for the given model classes during given callback scope.
362
     *
363
     * @param  array  $models
364
     * @param  callable  $callback
365
     * @return void
366
     */
367
    public static function withoutTouchingOn(array $models, callable $callback)
368
    {
369
        static::$ignoreOnTouch = array_values(array_merge(static::$ignoreOnTouch, $models));
370
 
371
        try {
372
            $callback();
373
        } finally {
374
            static::$ignoreOnTouch = array_values(array_diff(static::$ignoreOnTouch, $models));
375
        }
376
    }
377
 
378
    /**
379
     * Determine if the given model is ignoring touches.
380
     *
381
     * @param  string|null  $class
382
     * @return bool
383
     */
384
    public static function isIgnoringTouch($class = null)
385
    {
386
        $class = $class ?: static::class;
387
 
388
        if (! get_class_vars($class)['timestamps'] || ! $class::UPDATED_AT) {
389
            return true;
390
        }
391
 
392
        foreach (static::$ignoreOnTouch as $ignoredClass) {
393
            if ($class === $ignoredClass || is_subclass_of($class, $ignoredClass)) {
394
                return true;
395
            }
396
        }
397
 
398
        return false;
399
    }
400
 
401
    /**
402
     * Indicate that models should prevent lazy loading, silently discarding attributes, and accessing missing attributes.
403
     *
404
     * @param  bool  $shouldBeStrict
405
     * @return void
406
     */
407
    public static function shouldBeStrict(bool $shouldBeStrict = true)
408
    {
409
        static::preventLazyLoading($shouldBeStrict);
410
        static::preventSilentlyDiscardingAttributes($shouldBeStrict);
411
        static::preventAccessingMissingAttributes($shouldBeStrict);
412
    }
413
 
414
    /**
415
     * Prevent model relationships from being lazy loaded.
416
     *
417
     * @param  bool  $value
418
     * @return void
419
     */
420
    public static function preventLazyLoading($value = true)
421
    {
422
        static::$modelsShouldPreventLazyLoading = $value;
423
    }
424
 
425
    /**
426
     * Register a callback that is responsible for handling lazy loading violations.
427
     *
428
     * @param  callable|null  $callback
429
     * @return void
430
     */
431
    public static function handleLazyLoadingViolationUsing(?callable $callback)
432
    {
433
        static::$lazyLoadingViolationCallback = $callback;
434
    }
435
 
436
    /**
437
     * Prevent non-fillable attributes from being silently discarded.
438
     *
439
     * @param  bool  $value
440
     * @return void
441
     */
442
    public static function preventSilentlyDiscardingAttributes($value = true)
443
    {
444
        static::$modelsShouldPreventSilentlyDiscardingAttributes = $value;
445
    }
446
 
447
    /**
448
     * Register a callback that is responsible for handling discarded attribute violations.
449
     *
450
     * @param  callable|null  $callback
451
     * @return void
452
     */
453
    public static function handleDiscardedAttributeViolationUsing(?callable $callback)
454
    {
455
        static::$discardedAttributeViolationCallback = $callback;
456
    }
457
 
458
    /**
459
     * Prevent accessing missing attributes on retrieved models.
460
     *
461
     * @param  bool  $value
462
     * @return void
463
     */
464
    public static function preventAccessingMissingAttributes($value = true)
465
    {
466
        static::$modelsShouldPreventAccessingMissingAttributes = $value;
467
    }
468
 
469
    /**
470
     * Register a callback that is responsible for handling lazy loading violations.
471
     *
472
     * @param  callable|null  $callback
473
     * @return void
474
     */
475
    public static function handleMissingAttributeViolationUsing(?callable $callback)
476
    {
477
        static::$missingAttributeViolationCallback = $callback;
478
    }
479
 
480
    /**
481
     * Execute a callback without broadcasting any model events for all model types.
482
     *
483
     * @param  callable  $callback
484
     * @return mixed
485
     */
486
    public static function withoutBroadcasting(callable $callback)
487
    {
488
        $isBroadcasting = static::$isBroadcasting;
489
 
490
        static::$isBroadcasting = false;
491
 
492
        try {
493
            return $callback();
494
        } finally {
495
            static::$isBroadcasting = $isBroadcasting;
496
        }
497
    }
498
 
499
    /**
500
     * Fill the model with an array of attributes.
501
     *
502
     * @param  array  $attributes
503
     * @return $this
504
     *
505
     * @throws \Illuminate\Database\Eloquent\MassAssignmentException
506
     */
507
    public function fill(array $attributes)
508
    {
509
        $totallyGuarded = $this->totallyGuarded();
510
 
511
        $fillable = $this->fillableFromArray($attributes);
512
 
513
        foreach ($fillable as $key => $value) {
514
            // The developers may choose to place some attributes in the "fillable" array
515
            // which means only those attributes may be set through mass assignment to
516
            // the model, and all others will just get ignored for security reasons.
517
            if ($this->isFillable($key)) {
518
                $this->setAttribute($key, $value);
519
            } elseif ($totallyGuarded || static::preventsSilentlyDiscardingAttributes()) {
520
                if (isset(static::$discardedAttributeViolationCallback)) {
521
                    call_user_func(static::$discardedAttributeViolationCallback, $this, [$key]);
522
                } else {
523
                    throw new MassAssignmentException(sprintf(
524
                        'Add [%s] to fillable property to allow mass assignment on [%s].',
525
                        $key, get_class($this)
526
                    ));
527
                }
528
            }
529
        }
530
 
531
        if (count($attributes) !== count($fillable) &&
532
            static::preventsSilentlyDiscardingAttributes()) {
533
            $keys = array_diff(array_keys($attributes), array_keys($fillable));
534
 
535
            if (isset(static::$discardedAttributeViolationCallback)) {
536
                call_user_func(static::$discardedAttributeViolationCallback, $this, $keys);
537
            } else {
538
                throw new MassAssignmentException(sprintf(
539
                    'Add fillable property [%s] to allow mass assignment on [%s].',
540
                    implode(', ', $keys),
541
                    get_class($this)
542
                ));
543
            }
544
        }
545
 
546
        return $this;
547
    }
548
 
549
    /**
550
     * Fill the model with an array of attributes. Force mass assignment.
551
     *
552
     * @param  array  $attributes
553
     * @return $this
554
     */
555
    public function forceFill(array $attributes)
556
    {
557
        return static::unguarded(fn () => $this->fill($attributes));
558
    }
559
 
560
    /**
561
     * Qualify the given column name by the model's table.
562
     *
563
     * @param  string  $column
564
     * @return string
565
     */
566
    public function qualifyColumn($column)
567
    {
568
        if (str_contains($column, '.')) {
569
            return $column;
570
        }
571
 
572
        return $this->getTable().'.'.$column;
573
    }
574
 
575
    /**
576
     * Qualify the given columns with the model's table.
577
     *
578
     * @param  array  $columns
579
     * @return array
580
     */
581
    public function qualifyColumns($columns)
582
    {
583
        return collect($columns)->map(function ($column) {
584
            return $this->qualifyColumn($column);
585
        })->all();
586
    }
587
 
588
    /**
589
     * Create a new instance of the given model.
590
     *
591
     * @param  array  $attributes
592
     * @param  bool  $exists
593
     * @return static
594
     */
595
    public function newInstance($attributes = [], $exists = false)
596
    {
597
        // This method just provides a convenient way for us to generate fresh model
598
        // instances of this current model. It is particularly useful during the
599
        // hydration of new objects via the Eloquent query builder instances.
600
        $model = new static;
601
 
602
        $model->exists = $exists;
603
 
604
        $model->setConnection(
605
            $this->getConnectionName()
606
        );
607
 
608
        $model->setTable($this->getTable());
609
 
610
        $model->mergeCasts($this->casts);
611
 
612
        $model->fill((array) $attributes);
613
 
614
        return $model;
615
    }
616
 
617
    /**
618
     * Create a new model instance that is existing.
619
     *
620
     * @param  array  $attributes
621
     * @param  string|null  $connection
622
     * @return static
623
     */
624
    public function newFromBuilder($attributes = [], $connection = null)
625
    {
626
        $model = $this->newInstance([], true);
627
 
628
        $model->setRawAttributes((array) $attributes, true);
629
 
630
        $model->setConnection($connection ?: $this->getConnectionName());
631
 
632
        $model->fireModelEvent('retrieved', false);
633
 
634
        return $model;
635
    }
636
 
637
    /**
638
     * Begin querying the model on a given connection.
639
     *
640
     * @param  string|null  $connection
641
     * @return \Illuminate\Database\Eloquent\Builder
642
     */
643
    public static function on($connection = null)
644
    {
645
        // First we will just create a fresh instance of this model, and then we can set the
646
        // connection on the model so that it is used for the queries we execute, as well
647
        // as being set on every relation we retrieve without a custom connection name.
648
        $instance = new static;
649
 
650
        $instance->setConnection($connection);
651
 
652
        return $instance->newQuery();
653
    }
654
 
655
    /**
656
     * Begin querying the model on the write connection.
657
     *
658
     * @return \Illuminate\Database\Eloquent\Builder
659
     */
660
    public static function onWriteConnection()
661
    {
662
        return static::query()->useWritePdo();
663
    }
664
 
665
    /**
666
     * Get all of the models from the database.
667
     *
668
     * @param  array|string  $columns
669
     * @return \Illuminate\Database\Eloquent\Collection<int, static>
670
     */
671
    public static function all($columns = ['*'])
672
    {
673
        return static::query()->get(
674
            is_array($columns) ? $columns : func_get_args()
675
        );
676
    }
677
 
678
    /**
679
     * Begin querying a model with eager loading.
680
     *
681
     * @param  array|string  $relations
682
     * @return \Illuminate\Database\Eloquent\Builder
683
     */
684
    public static function with($relations)
685
    {
686
        return static::query()->with(
687
            is_string($relations) ? func_get_args() : $relations
688
        );
689
    }
690
 
691
    /**
692
     * Eager load relations on the model.
693
     *
694
     * @param  array|string  $relations
695
     * @return $this
696
     */
697
    public function load($relations)
698
    {
699
        $query = $this->newQueryWithoutRelationships()->with(
700
            is_string($relations) ? func_get_args() : $relations
701
        );
702
 
703
        $query->eagerLoadRelations([$this]);
704
 
705
        return $this;
706
    }
707
 
708
    /**
709
     * Eager load relationships on the polymorphic relation of a model.
710
     *
711
     * @param  string  $relation
712
     * @param  array  $relations
713
     * @return $this
714
     */
715
    public function loadMorph($relation, $relations)
716
    {
717
        if (! $this->{$relation}) {
718
            return $this;
719
        }
720
 
721
        $className = get_class($this->{$relation});
722
 
723
        $this->{$relation}->load($relations[$className] ?? []);
724
 
725
        return $this;
726
    }
727
 
728
    /**
729
     * Eager load relations on the model if they are not already eager loaded.
730
     *
731
     * @param  array|string  $relations
732
     * @return $this
733
     */
734
    public function loadMissing($relations)
735
    {
736
        $relations = is_string($relations) ? func_get_args() : $relations;
737
 
738
        $this->newCollection([$this])->loadMissing($relations);
739
 
740
        return $this;
741
    }
742
 
743
    /**
744
     * Eager load relation's column aggregations on the model.
745
     *
746
     * @param  array|string  $relations
747
     * @param  string  $column
748
     * @param  string  $function
749
     * @return $this
750
     */
751
    public function loadAggregate($relations, $column, $function = null)
752
    {
753
        $this->newCollection([$this])->loadAggregate($relations, $column, $function);
754
 
755
        return $this;
756
    }
757
 
758
    /**
759
     * Eager load relation counts on the model.
760
     *
761
     * @param  array|string  $relations
762
     * @return $this
763
     */
764
    public function loadCount($relations)
765
    {
766
        $relations = is_string($relations) ? func_get_args() : $relations;
767
 
768
        return $this->loadAggregate($relations, '*', 'count');
769
    }
770
 
771
    /**
772
     * Eager load relation max column values on the model.
773
     *
774
     * @param  array|string  $relations
775
     * @param  string  $column
776
     * @return $this
777
     */
778
    public function loadMax($relations, $column)
779
    {
780
        return $this->loadAggregate($relations, $column, 'max');
781
    }
782
 
783
    /**
784
     * Eager load relation min column values on the model.
785
     *
786
     * @param  array|string  $relations
787
     * @param  string  $column
788
     * @return $this
789
     */
790
    public function loadMin($relations, $column)
791
    {
792
        return $this->loadAggregate($relations, $column, 'min');
793
    }
794
 
795
    /**
796
     * Eager load relation's column summations on the model.
797
     *
798
     * @param  array|string  $relations
799
     * @param  string  $column
800
     * @return $this
801
     */
802
    public function loadSum($relations, $column)
803
    {
804
        return $this->loadAggregate($relations, $column, 'sum');
805
    }
806
 
807
    /**
808
     * Eager load relation average column values on the model.
809
     *
810
     * @param  array|string  $relations
811
     * @param  string  $column
812
     * @return $this
813
     */
814
    public function loadAvg($relations, $column)
815
    {
816
        return $this->loadAggregate($relations, $column, 'avg');
817
    }
818
 
819
    /**
820
     * Eager load related model existence values on the model.
821
     *
822
     * @param  array|string  $relations
823
     * @return $this
824
     */
825
    public function loadExists($relations)
826
    {
827
        return $this->loadAggregate($relations, '*', 'exists');
828
    }
829
 
830
    /**
831
     * Eager load relationship column aggregation on the polymorphic relation of a model.
832
     *
833
     * @param  string  $relation
834
     * @param  array  $relations
835
     * @param  string  $column
836
     * @param  string  $function
837
     * @return $this
838
     */
839
    public function loadMorphAggregate($relation, $relations, $column, $function = null)
840
    {
841
        if (! $this->{$relation}) {
842
            return $this;
843
        }
844
 
845
        $className = get_class($this->{$relation});
846
 
847
        $this->{$relation}->loadAggregate($relations[$className] ?? [], $column, $function);
848
 
849
        return $this;
850
    }
851
 
852
    /**
853
     * Eager load relationship counts on the polymorphic relation of a model.
854
     *
855
     * @param  string  $relation
856
     * @param  array  $relations
857
     * @return $this
858
     */
859
    public function loadMorphCount($relation, $relations)
860
    {
861
        return $this->loadMorphAggregate($relation, $relations, '*', 'count');
862
    }
863
 
864
    /**
865
     * Eager load relationship max column values on the polymorphic relation of a model.
866
     *
867
     * @param  string  $relation
868
     * @param  array  $relations
869
     * @param  string  $column
870
     * @return $this
871
     */
872
    public function loadMorphMax($relation, $relations, $column)
873
    {
874
        return $this->loadMorphAggregate($relation, $relations, $column, 'max');
875
    }
876
 
877
    /**
878
     * Eager load relationship min column values on the polymorphic relation of a model.
879
     *
880
     * @param  string  $relation
881
     * @param  array  $relations
882
     * @param  string  $column
883
     * @return $this
884
     */
885
    public function loadMorphMin($relation, $relations, $column)
886
    {
887
        return $this->loadMorphAggregate($relation, $relations, $column, 'min');
888
    }
889
 
890
    /**
891
     * Eager load relationship column summations on the polymorphic relation of a model.
892
     *
893
     * @param  string  $relation
894
     * @param  array  $relations
895
     * @param  string  $column
896
     * @return $this
897
     */
898
    public function loadMorphSum($relation, $relations, $column)
899
    {
900
        return $this->loadMorphAggregate($relation, $relations, $column, 'sum');
901
    }
902
 
903
    /**
904
     * Eager load relationship average column values on the polymorphic relation of a model.
905
     *
906
     * @param  string  $relation
907
     * @param  array  $relations
908
     * @param  string  $column
909
     * @return $this
910
     */
911
    public function loadMorphAvg($relation, $relations, $column)
912
    {
913
        return $this->loadMorphAggregate($relation, $relations, $column, 'avg');
914
    }
915
 
916
    /**
917
     * Increment a column's value by a given amount.
918
     *
919
     * @param  string  $column
920
     * @param  float|int  $amount
921
     * @param  array  $extra
922
     * @return int
923
     */
924
    protected function increment($column, $amount = 1, array $extra = [])
925
    {
926
        return $this->incrementOrDecrement($column, $amount, $extra, 'increment');
927
    }
928
 
929
    /**
930
     * Decrement a column's value by a given amount.
931
     *
932
     * @param  string  $column
933
     * @param  float|int  $amount
934
     * @param  array  $extra
935
     * @return int
936
     */
937
    protected function decrement($column, $amount = 1, array $extra = [])
938
    {
939
        return $this->incrementOrDecrement($column, $amount, $extra, 'decrement');
940
    }
941
 
942
    /**
943
     * Run the increment or decrement method on the model.
944
     *
945
     * @param  string  $column
946
     * @param  float|int  $amount
947
     * @param  array  $extra
948
     * @param  string  $method
949
     * @return int
950
     */
951
    protected function incrementOrDecrement($column, $amount, $extra, $method)
952
    {
953
        $query = $this->newQueryWithoutRelationships();
954
 
955
        if (! $this->exists) {
956
            return $query->{$method}($column, $amount, $extra);
957
        }
958
 
959
        $this->{$column} = $this->isClassDeviable($column)
960
            ? $this->deviateClassCastableAttribute($method, $column, $amount)
961
            : $this->{$column} + ($method === 'increment' ? $amount : $amount * -1);
962
 
963
        $this->forceFill($extra);
964
 
965
        if ($this->fireModelEvent('updating') === false) {
966
            return false;
967
        }
968
 
969
        return tap($this->setKeysForSaveQuery($query)->{$method}($column, $amount, $extra), function () use ($column) {
970
            $this->syncChanges();
971
 
972
            $this->fireModelEvent('updated', false);
973
 
974
            $this->syncOriginalAttribute($column);
975
        });
976
    }
977
 
978
    /**
979
     * Update the model in the database.
980
     *
981
     * @param  array  $attributes
982
     * @param  array  $options
983
     * @return bool
984
     */
985
    public function update(array $attributes = [], array $options = [])
986
    {
987
        if (! $this->exists) {
988
            return false;
989
        }
990
 
991
        return $this->fill($attributes)->save($options);
992
    }
993
 
994
    /**
995
     * Update the model in the database within a transaction.
996
     *
997
     * @param  array  $attributes
998
     * @param  array  $options
999
     * @return bool
1000
     *
1001
     * @throws \Throwable
1002
     */
1003
    public function updateOrFail(array $attributes = [], array $options = [])
1004
    {
1005
        if (! $this->exists) {
1006
            return false;
1007
        }
1008
 
1009
        return $this->fill($attributes)->saveOrFail($options);
1010
    }
1011
 
1012
    /**
1013
     * Update the model in the database without raising any events.
1014
     *
1015
     * @param  array  $attributes
1016
     * @param  array  $options
1017
     * @return bool
1018
     */
1019
    public function updateQuietly(array $attributes = [], array $options = [])
1020
    {
1021
        if (! $this->exists) {
1022
            return false;
1023
        }
1024
 
1025
        return $this->fill($attributes)->saveQuietly($options);
1026
    }
1027
 
1028
    /**
1029
     * Increment a column's value by a given amount without raising any events.
1030
     *
1031
     * @param  string  $column
1032
     * @param  float|int  $amount
1033
     * @param  array  $extra
1034
     * @return int
1035
     */
1036
    protected function incrementQuietly($column, $amount = 1, array $extra = [])
1037
    {
1038
        return static::withoutEvents(function () use ($column, $amount, $extra) {
1039
            return $this->incrementOrDecrement($column, $amount, $extra, 'increment');
1040
        });
1041
    }
1042
 
1043
    /**
1044
     * Decrement a column's value by a given amount without raising any events.
1045
     *
1046
     * @param  string  $column
1047
     * @param  float|int  $amount
1048
     * @param  array  $extra
1049
     * @return int
1050
     */
1051
    protected function decrementQuietly($column, $amount = 1, array $extra = [])
1052
    {
1053
        return static::withoutEvents(function () use ($column, $amount, $extra) {
1054
            return $this->incrementOrDecrement($column, $amount, $extra, 'decrement');
1055
        });
1056
    }
1057
 
1058
    /**
1059
     * Save the model and all of its relationships.
1060
     *
1061
     * @return bool
1062
     */
1063
    public function push()
1064
    {
1065
        if (! $this->save()) {
1066
            return false;
1067
        }
1068
 
1069
        // To sync all of the relationships to the database, we will simply spin through
1070
        // the relationships and save each model via this "push" method, which allows
1071
        // us to recurse into all of these nested relations for the model instance.
1072
        foreach ($this->relations as $models) {
1073
            $models = $models instanceof Collection
1074
                ? $models->all() : [$models];
1075
 
1076
            foreach (array_filter($models) as $model) {
1077
                if (! $model->push()) {
1078
                    return false;
1079
                }
1080
            }
1081
        }
1082
 
1083
        return true;
1084
    }
1085
 
1086
    /**
1087
     * Save the model to the database without raising any events.
1088
     *
1089
     * @param  array  $options
1090
     * @return bool
1091
     */
1092
    public function saveQuietly(array $options = [])
1093
    {
1094
        return static::withoutEvents(fn () => $this->save($options));
1095
    }
1096
 
1097
    /**
1098
     * Save the model to the database.
1099
     *
1100
     * @param  array  $options
1101
     * @return bool
1102
     */
1103
    public function save(array $options = [])
1104
    {
1105
        $this->mergeAttributesFromCachedCasts();
1106
 
1107
        $query = $this->newModelQuery();
1108
 
1109
        // If the "saving" event returns false we'll bail out of the save and return
1110
        // false, indicating that the save failed. This provides a chance for any
1111
        // listeners to cancel save operations if validations fail or whatever.
1112
        if ($this->fireModelEvent('saving') === false) {
1113
            return false;
1114
        }
1115
 
1116
        // If the model already exists in the database we can just update our record
1117
        // that is already in this database using the current IDs in this "where"
1118
        // clause to only update this model. Otherwise, we'll just insert them.
1119
        if ($this->exists) {
1120
            $saved = $this->isDirty() ?
1121
                $this->performUpdate($query) : true;
1122
        }
1123
 
1124
        // If the model is brand new, we'll insert it into our database and set the
1125
        // ID attribute on the model to the value of the newly inserted row's ID
1126
        // which is typically an auto-increment value managed by the database.
1127
        else {
1128
            $saved = $this->performInsert($query);
1129
 
1130
            if (! $this->getConnectionName() &&
1131
                $connection = $query->getConnection()) {
1132
                $this->setConnection($connection->getName());
1133
            }
1134
        }
1135
 
1136
        // If the model is successfully saved, we need to do a few more things once
1137
        // that is done. We will call the "saved" method here to run any actions
1138
        // we need to happen after a model gets successfully saved right here.
1139
        if ($saved) {
1140
            $this->finishSave($options);
1141
        }
1142
 
1143
        return $saved;
1144
    }
1145
 
1146
    /**
1147
     * Save the model to the database within a transaction.
1148
     *
1149
     * @param  array  $options
1150
     * @return bool
1151
     *
1152
     * @throws \Throwable
1153
     */
1154
    public function saveOrFail(array $options = [])
1155
    {
1156
        return $this->getConnection()->transaction(fn () => $this->save($options));
1157
    }
1158
 
1159
    /**
1160
     * Perform any actions that are necessary after the model is saved.
1161
     *
1162
     * @param  array  $options
1163
     * @return void
1164
     */
1165
    protected function finishSave(array $options)
1166
    {
1167
        $this->fireModelEvent('saved', false);
1168
 
1169
        if ($this->isDirty() && ($options['touch'] ?? true)) {
1170
            $this->touchOwners();
1171
        }
1172
 
1173
        $this->syncOriginal();
1174
    }
1175
 
1176
    /**
1177
     * Perform a model update operation.
1178
     *
1179
     * @param  \Illuminate\Database\Eloquent\Builder  $query
1180
     * @return bool
1181
     */
1182
    protected function performUpdate(Builder $query)
1183
    {
1184
        // If the updating event returns false, we will cancel the update operation so
1185
        // developers can hook Validation systems into their models and cancel this
1186
        // operation if the model does not pass validation. Otherwise, we update.
1187
        if ($this->fireModelEvent('updating') === false) {
1188
            return false;
1189
        }
1190
 
1191
        // First we need to create a fresh query instance and touch the creation and
1192
        // update timestamp on the model which are maintained by us for developer
1193
        // convenience. Then we will just continue saving the model instances.
1194
        if ($this->usesTimestamps()) {
1195
            $this->updateTimestamps();
1196
        }
1197
 
1198
        // Once we have run the update operation, we will fire the "updated" event for
1199
        // this model instance. This will allow developers to hook into these after
1200
        // models are updated, giving them a chance to do any special processing.
1201
        $dirty = $this->getDirty();
1202
 
1203
        if (count($dirty) > 0) {
1204
            $this->setKeysForSaveQuery($query)->update($dirty);
1205
 
1206
            $this->syncChanges();
1207
 
1208
            $this->fireModelEvent('updated', false);
1209
        }
1210
 
1211
        return true;
1212
    }
1213
 
1214
    /**
1215
     * Set the keys for a select query.
1216
     *
1217
     * @param  \Illuminate\Database\Eloquent\Builder  $query
1218
     * @return \Illuminate\Database\Eloquent\Builder
1219
     */
1220
    protected function setKeysForSelectQuery($query)
1221
    {
1222
        $query->where($this->getKeyName(), '=', $this->getKeyForSelectQuery());
1223
 
1224
        return $query;
1225
    }
1226
 
1227
    /**
1228
     * Get the primary key value for a select query.
1229
     *
1230
     * @return mixed
1231
     */
1232
    protected function getKeyForSelectQuery()
1233
    {
1234
        return $this->original[$this->getKeyName()] ?? $this->getKey();
1235
    }
1236
 
1237
    /**
1238
     * Set the keys for a save update query.
1239
     *
1240
     * @param  \Illuminate\Database\Eloquent\Builder  $query
1241
     * @return \Illuminate\Database\Eloquent\Builder
1242
     */
1243
    protected function setKeysForSaveQuery($query)
1244
    {
1245
        $query->where($this->getKeyName(), '=', $this->getKeyForSaveQuery());
1246
 
1247
        return $query;
1248
    }
1249
 
1250
    /**
1251
     * Get the primary key value for a save query.
1252
     *
1253
     * @return mixed
1254
     */
1255
    protected function getKeyForSaveQuery()
1256
    {
1257
        return $this->original[$this->getKeyName()] ?? $this->getKey();
1258
    }
1259
 
1260
    /**
1261
     * Perform a model insert operation.
1262
     *
1263
     * @param  \Illuminate\Database\Eloquent\Builder  $query
1264
     * @return bool
1265
     */
1266
    protected function performInsert(Builder $query)
1267
    {
1268
        if ($this->fireModelEvent('creating') === false) {
1269
            return false;
1270
        }
1271
 
1272
        // First we'll need to create a fresh query instance and touch the creation and
1273
        // update timestamps on this model, which are maintained by us for developer
1274
        // convenience. After, we will just continue saving these model instances.
1275
        if ($this->usesTimestamps()) {
1276
            $this->updateTimestamps();
1277
        }
1278
 
1279
        // If the model has an incrementing key, we can use the "insertGetId" method on
1280
        // the query builder, which will give us back the final inserted ID for this
1281
        // table from the database. Not all tables have to be incrementing though.
1282
        $attributes = $this->getAttributesForInsert();
1283
 
1284
        if ($this->getIncrementing()) {
1285
            $this->insertAndSetId($query, $attributes);
1286
        }
1287
 
1288
        // If the table isn't incrementing we'll simply insert these attributes as they
1289
        // are. These attribute arrays must contain an "id" column previously placed
1290
        // there by the developer as the manually determined key for these models.
1291
        else {
1292
            if (empty($attributes)) {
1293
                return true;
1294
            }
1295
 
1296
            $query->insert($attributes);
1297
        }
1298
 
1299
        // We will go ahead and set the exists property to true, so that it is set when
1300
        // the created event is fired, just in case the developer tries to update it
1301
        // during the event. This will allow them to do so and run an update here.
1302
        $this->exists = true;
1303
 
1304
        $this->wasRecentlyCreated = true;
1305
 
1306
        $this->fireModelEvent('created', false);
1307
 
1308
        return true;
1309
    }
1310
 
1311
    /**
1312
     * Insert the given attributes and set the ID on the model.
1313
     *
1314
     * @param  \Illuminate\Database\Eloquent\Builder  $query
1315
     * @param  array  $attributes
1316
     * @return void
1317
     */
1318
    protected function insertAndSetId(Builder $query, $attributes)
1319
    {
1320
        $id = $query->insertGetId($attributes, $keyName = $this->getKeyName());
1321
 
1322
        $this->setAttribute($keyName, $id);
1323
    }
1324
 
1325
    /**
1326
     * Destroy the models for the given IDs.
1327
     *
1328
     * @param  \Illuminate\Support\Collection|array|int|string  $ids
1329
     * @return int
1330
     */
1331
    public static function destroy($ids)
1332
    {
1333
        if ($ids instanceof EloquentCollection) {
1334
            $ids = $ids->modelKeys();
1335
        }
1336
 
1337
        if ($ids instanceof BaseCollection) {
1338
            $ids = $ids->all();
1339
        }
1340
 
1341
        $ids = is_array($ids) ? $ids : func_get_args();
1342
 
1343
        if (count($ids) === 0) {
1344
            return 0;
1345
        }
1346
 
1347
        // We will actually pull the models from the database table and call delete on
1348
        // each of them individually so that their events get fired properly with a
1349
        // correct set of attributes in case the developers wants to check these.
1350
        $key = ($instance = new static)->getKeyName();
1351
 
1352
        $count = 0;
1353
 
1354
        foreach ($instance->whereIn($key, $ids)->get() as $model) {
1355
            if ($model->delete()) {
1356
                $count++;
1357
            }
1358
        }
1359
 
1360
        return $count;
1361
    }
1362
 
1363
    /**
1364
     * Delete the model from the database.
1365
     *
1366
     * @return bool|null
1367
     *
1368
     * @throws \LogicException
1369
     */
1370
    public function delete()
1371
    {
1372
        $this->mergeAttributesFromCachedCasts();
1373
 
1374
        if (is_null($this->getKeyName())) {
1375
            throw new LogicException('No primary key defined on model.');
1376
        }
1377
 
1378
        // If the model doesn't exist, there is nothing to delete so we'll just return
1379
        // immediately and not do anything else. Otherwise, we will continue with a
1380
        // deletion process on the model, firing the proper events, and so forth.
1381
        if (! $this->exists) {
1382
            return;
1383
        }
1384
 
1385
        if ($this->fireModelEvent('deleting') === false) {
1386
            return false;
1387
        }
1388
 
1389
        // Here, we'll touch the owning models, verifying these timestamps get updated
1390
        // for the models. This will allow any caching to get broken on the parents
1391
        // by the timestamp. Then we will go ahead and delete the model instance.
1392
        $this->touchOwners();
1393
 
1394
        $this->performDeleteOnModel();
1395
 
1396
        // Once the model has been deleted, we will fire off the deleted event so that
1397
        // the developers may hook into post-delete operations. We will then return
1398
        // a boolean true as the delete is presumably successful on the database.
1399
        $this->fireModelEvent('deleted', false);
1400
 
1401
        return true;
1402
    }
1403
 
1404
    /**
1405
     * Delete the model from the database without raising any events.
1406
     *
1407
     * @return bool
1408
     */
1409
    public function deleteQuietly()
1410
    {
1411
        return static::withoutEvents(fn () => $this->delete());
1412
    }
1413
 
1414
    /**
1415
     * Delete the model from the database within a transaction.
1416
     *
1417
     * @return bool|null
1418
     *
1419
     * @throws \Throwable
1420
     */
1421
    public function deleteOrFail()
1422
    {
1423
        if (! $this->exists) {
1424
            return false;
1425
        }
1426
 
1427
        return $this->getConnection()->transaction(fn () => $this->delete());
1428
    }
1429
 
1430
    /**
1431
     * Force a hard delete on a soft deleted model.
1432
     *
1433
     * This method protects developers from running forceDelete when the trait is missing.
1434
     *
1435
     * @return bool|null
1436
     */
1437
    public function forceDelete()
1438
    {
1439
        return $this->delete();
1440
    }
1441
 
1442
    /**
1443
     * Perform the actual delete query on this model instance.
1444
     *
1445
     * @return void
1446
     */
1447
    protected function performDeleteOnModel()
1448
    {
1449
        $this->setKeysForSaveQuery($this->newModelQuery())->delete();
1450
 
1451
        $this->exists = false;
1452
    }
1453
 
1454
    /**
1455
     * Begin querying the model.
1456
     *
1457
     * @return \Illuminate\Database\Eloquent\Builder
1458
     */
1459
    public static function query()
1460
    {
1461
        return (new static)->newQuery();
1462
    }
1463
 
1464
    /**
1465
     * Get a new query builder for the model's table.
1466
     *
1467
     * @return \Illuminate\Database\Eloquent\Builder
1468
     */
1469
    public function newQuery()
1470
    {
1471
        return $this->registerGlobalScopes($this->newQueryWithoutScopes());
1472
    }
1473
 
1474
    /**
1475
     * Get a new query builder that doesn't have any global scopes or eager loading.
1476
     *
1477
     * @return \Illuminate\Database\Eloquent\Builder|static
1478
     */
1479
    public function newModelQuery()
1480
    {
1481
        return $this->newEloquentBuilder(
1482
            $this->newBaseQueryBuilder()
1483
        )->setModel($this);
1484
    }
1485
 
1486
    /**
1487
     * Get a new query builder with no relationships loaded.
1488
     *
1489
     * @return \Illuminate\Database\Eloquent\Builder
1490
     */
1491
    public function newQueryWithoutRelationships()
1492
    {
1493
        return $this->registerGlobalScopes($this->newModelQuery());
1494
    }
1495
 
1496
    /**
1497
     * Register the global scopes for this builder instance.
1498
     *
1499
     * @param  \Illuminate\Database\Eloquent\Builder  $builder
1500
     * @return \Illuminate\Database\Eloquent\Builder
1501
     */
1502
    public function registerGlobalScopes($builder)
1503
    {
1504
        foreach ($this->getGlobalScopes() as $identifier => $scope) {
1505
            $builder->withGlobalScope($identifier, $scope);
1506
        }
1507
 
1508
        return $builder;
1509
    }
1510
 
1511
    /**
1512
     * Get a new query builder that doesn't have any global scopes.
1513
     *
1514
     * @return \Illuminate\Database\Eloquent\Builder|static
1515
     */
1516
    public function newQueryWithoutScopes()
1517
    {
1518
        return $this->newModelQuery()
1519
            ->with($this->with)
1520
            ->withCount($this->withCount);
1521
    }
1522
 
1523
    /**
1524
     * Get a new query instance without a given scope.
1525
     *
1526
     * @param  \Illuminate\Database\Eloquent\Scope|string  $scope
1527
     * @return \Illuminate\Database\Eloquent\Builder
1528
     */
1529
    public function newQueryWithoutScope($scope)
1530
    {
1531
        return $this->newQuery()->withoutGlobalScope($scope);
1532
    }
1533
 
1534
    /**
1535
     * Get a new query to restore one or more models by their queueable IDs.
1536
     *
1537
     * @param  array|int  $ids
1538
     * @return \Illuminate\Database\Eloquent\Builder
1539
     */
1540
    public function newQueryForRestoration($ids)
1541
    {
1542
        return $this->newQueryWithoutScopes()->whereKey($ids);
1543
    }
1544
 
1545
    /**
1546
     * Create a new Eloquent query builder for the model.
1547
     *
1548
     * @param  \Illuminate\Database\Query\Builder  $query
1549
     * @return \Illuminate\Database\Eloquent\Builder|static
1550
     */
1551
    public function newEloquentBuilder($query)
1552
    {
1553
        return new Builder($query);
1554
    }
1555
 
1556
    /**
1557
     * Get a new query builder instance for the connection.
1558
     *
1559
     * @return \Illuminate\Database\Query\Builder
1560
     */
1561
    protected function newBaseQueryBuilder()
1562
    {
1563
        return $this->getConnection()->query();
1564
    }
1565
 
1566
    /**
1567
     * Create a new Eloquent Collection instance.
1568
     *
1569
     * @param  array  $models
1570
     * @return \Illuminate\Database\Eloquent\Collection
1571
     */
1572
    public function newCollection(array $models = [])
1573
    {
1574
        return new Collection($models);
1575
    }
1576
 
1577
    /**
1578
     * Create a new pivot model instance.
1579
     *
1580
     * @param  \Illuminate\Database\Eloquent\Model  $parent
1581
     * @param  array  $attributes
1582
     * @param  string  $table
1583
     * @param  bool  $exists
1584
     * @param  string|null  $using
1585
     * @return \Illuminate\Database\Eloquent\Relations\Pivot
1586
     */
1587
    public function newPivot(self $parent, array $attributes, $table, $exists, $using = null)
1588
    {
1589
        return $using ? $using::fromRawAttributes($parent, $attributes, $table, $exists)
1590
            : Pivot::fromAttributes($parent, $attributes, $table, $exists);
1591
    }
1592
 
1593
    /**
1594
     * Determine if the model has a given scope.
1595
     *
1596
     * @param  string  $scope
1597
     * @return bool
1598
     */
1599
    public function hasNamedScope($scope)
1600
    {
1601
        return method_exists($this, 'scope'.ucfirst($scope));
1602
    }
1603
 
1604
    /**
1605
     * Apply the given named scope if possible.
1606
     *
1607
     * @param  string  $scope
1608
     * @param  array  $parameters
1609
     * @return mixed
1610
     */
1611
    public function callNamedScope($scope, array $parameters = [])
1612
    {
1613
        return $this->{'scope'.ucfirst($scope)}(...$parameters);
1614
    }
1615
 
1616
    /**
1617
     * Convert the model instance to an array.
1618
     *
1619
     * @return array
1620
     */
1621
    public function toArray()
1622
    {
1623
        return array_merge($this->attributesToArray(), $this->relationsToArray());
1624
    }
1625
 
1626
    /**
1627
     * Convert the model instance to JSON.
1628
     *
1629
     * @param  int  $options
1630
     * @return string
1631
     *
1632
     * @throws \Illuminate\Database\Eloquent\JsonEncodingException
1633
     */
1634
    public function toJson($options = 0)
1635
    {
1636
        $json = json_encode($this->jsonSerialize(), $options);
1637
 
1638
        if (json_last_error() !== JSON_ERROR_NONE) {
1639
            throw JsonEncodingException::forModel($this, json_last_error_msg());
1640
        }
1641
 
1642
        return $json;
1643
    }
1644
 
1645
    /**
1646
     * Convert the object into something JSON serializable.
1647
     *
1648
     * @return mixed
1649
     */
1650
    public function jsonSerialize(): mixed
1651
    {
1652
        return $this->toArray();
1653
    }
1654
 
1655
    /**
1656
     * Reload a fresh model instance from the database.
1657
     *
1658
     * @param  array|string  $with
1659
     * @return static|null
1660
     */
1661
    public function fresh($with = [])
1662
    {
1663
        if (! $this->exists) {
1664
            return;
1665
        }
1666
 
1667
        return $this->setKeysForSelectQuery($this->newQueryWithoutScopes())
1668
            ->useWritePdo()
1669
            ->with(is_string($with) ? func_get_args() : $with)
1670
            ->first();
1671
    }
1672
 
1673
    /**
1674
     * Reload the current model instance with fresh attributes from the database.
1675
     *
1676
     * @return $this
1677
     */
1678
    public function refresh()
1679
    {
1680
        if (! $this->exists) {
1681
            return $this;
1682
        }
1683
 
1684
        $this->setRawAttributes(
1685
            $this->setKeysForSelectQuery($this->newQueryWithoutScopes())
1686
                ->useWritePdo()
1687
                ->firstOrFail()
1688
                ->attributes
1689
        );
1690
 
1691
        $this->load(collect($this->relations)->reject(function ($relation) {
1692
            return $relation instanceof Pivot
1693
                || (is_object($relation) && in_array(AsPivot::class, class_uses_recursive($relation), true));
1694
        })->keys()->all());
1695
 
1696
        $this->syncOriginal();
1697
 
1698
        return $this;
1699
    }
1700
 
1701
    /**
1702
     * Clone the model into a new, non-existing instance.
1703
     *
1704
     * @param  array|null  $except
1705
     * @return static
1706
     */
1707
    public function replicate(array $except = null)
1708
    {
1709
        $defaults = array_values(array_filter([
1710
            $this->getKeyName(),
1711
            $this->getCreatedAtColumn(),
1712
            $this->getUpdatedAtColumn(),
1713
        ]));
1714
 
1715
        $attributes = Arr::except(
1716
            $this->getAttributes(), $except ? array_unique(array_merge($except, $defaults)) : $defaults
1717
        );
1718
 
1719
        return tap(new static, function ($instance) use ($attributes) {
1720
            $instance->setRawAttributes($attributes);
1721
 
1722
            $instance->setRelations($this->relations);
1723
 
1724
            $instance->fireModelEvent('replicating', false);
1725
        });
1726
    }
1727
 
1728
    /**
1729
     * Clone the model into a new, non-existing instance without raising any events.
1730
     *
1731
     * @param  array|null  $except
1732
     * @return static
1733
     */
1734
    public function replicateQuietly(array $except = null)
1735
    {
1736
        return static::withoutEvents(fn () => $this->replicate($except));
1737
    }
1738
 
1739
    /**
1740
     * Determine if two models have the same ID and belong to the same table.
1741
     *
1742
     * @param  \Illuminate\Database\Eloquent\Model|null  $model
1743
     * @return bool
1744
     */
1745
    public function is($model)
1746
    {
1747
        return ! is_null($model) &&
1748
            $this->getKey() === $model->getKey() &&
1749
            $this->getTable() === $model->getTable() &&
1750
            $this->getConnectionName() === $model->getConnectionName();
1751
    }
1752
 
1753
    /**
1754
     * Determine if two models are not the same.
1755
     *
1756
     * @param  \Illuminate\Database\Eloquent\Model|null  $model
1757
     * @return bool
1758
     */
1759
    public function isNot($model)
1760
    {
1761
        return ! $this->is($model);
1762
    }
1763
 
1764
    /**
1765
     * Get the database connection for the model.
1766
     *
1767
     * @return \Illuminate\Database\Connection
1768
     */
1769
    public function getConnection()
1770
    {
1771
        return static::resolveConnection($this->getConnectionName());
1772
    }
1773
 
1774
    /**
1775
     * Get the current connection name for the model.
1776
     *
1777
     * @return string|null
1778
     */
1779
    public function getConnectionName()
1780
    {
1781
        return $this->connection;
1782
    }
1783
 
1784
    /**
1785
     * Set the connection associated with the model.
1786
     *
1787
     * @param  string|null  $name
1788
     * @return $this
1789
     */
1790
    public function setConnection($name)
1791
    {
1792
        $this->connection = $name;
1793
 
1794
        return $this;
1795
    }
1796
 
1797
    /**
1798
     * Resolve a connection instance.
1799
     *
1800
     * @param  string|null  $connection
1801
     * @return \Illuminate\Database\Connection
1802
     */
1803
    public static function resolveConnection($connection = null)
1804
    {
1805
        return static::$resolver->connection($connection);
1806
    }
1807
 
1808
    /**
1809
     * Get the connection resolver instance.
1810
     *
1811
     * @return \Illuminate\Database\ConnectionResolverInterface
1812
     */
1813
    public static function getConnectionResolver()
1814
    {
1815
        return static::$resolver;
1816
    }
1817
 
1818
    /**
1819
     * Set the connection resolver instance.
1820
     *
1821
     * @param  \Illuminate\Database\ConnectionResolverInterface  $resolver
1822
     * @return void
1823
     */
1824
    public static function setConnectionResolver(Resolver $resolver)
1825
    {
1826
        static::$resolver = $resolver;
1827
    }
1828
 
1829
    /**
1830
     * Unset the connection resolver for models.
1831
     *
1832
     * @return void
1833
     */
1834
    public static function unsetConnectionResolver()
1835
    {
1836
        static::$resolver = null;
1837
    }
1838
 
1839
    /**
1840
     * Get the table associated with the model.
1841
     *
1842
     * @return string
1843
     */
1844
    public function getTable()
1845
    {
1846
        return $this->table ?? Str::snake(Str::pluralStudly(class_basename($this)));
1847
    }
1848
 
1849
    /**
1850
     * Set the table associated with the model.
1851
     *
1852
     * @param  string  $table
1853
     * @return $this
1854
     */
1855
    public function setTable($table)
1856
    {
1857
        $this->table = $table;
1858
 
1859
        return $this;
1860
    }
1861
 
1862
    /**
1863
     * Get the primary key for the model.
1864
     *
1865
     * @return string
1866
     */
1867
    public function getKeyName()
1868
    {
1869
        return $this->primaryKey;
1870
    }
1871
 
1872
    /**
1873
     * Set the primary key for the model.
1874
     *
1875
     * @param  string  $key
1876
     * @return $this
1877
     */
1878
    public function setKeyName($key)
1879
    {
1880
        $this->primaryKey = $key;
1881
 
1882
        return $this;
1883
    }
1884
 
1885
    /**
1886
     * Get the table qualified key name.
1887
     *
1888
     * @return string
1889
     */
1890
    public function getQualifiedKeyName()
1891
    {
1892
        return $this->qualifyColumn($this->getKeyName());
1893
    }
1894
 
1895
    /**
1896
     * Get the auto-incrementing key type.
1897
     *
1898
     * @return string
1899
     */
1900
    public function getKeyType()
1901
    {
1902
        return $this->keyType;
1903
    }
1904
 
1905
    /**
1906
     * Set the data type for the primary key.
1907
     *
1908
     * @param  string  $type
1909
     * @return $this
1910
     */
1911
    public function setKeyType($type)
1912
    {
1913
        $this->keyType = $type;
1914
 
1915
        return $this;
1916
    }
1917
 
1918
    /**
1919
     * Get the value indicating whether the IDs are incrementing.
1920
     *
1921
     * @return bool
1922
     */
1923
    public function getIncrementing()
1924
    {
1925
        return $this->incrementing;
1926
    }
1927
 
1928
    /**
1929
     * Set whether IDs are incrementing.
1930
     *
1931
     * @param  bool  $value
1932
     * @return $this
1933
     */
1934
    public function setIncrementing($value)
1935
    {
1936
        $this->incrementing = $value;
1937
 
1938
        return $this;
1939
    }
1940
 
1941
    /**
1942
     * Get the value of the model's primary key.
1943
     *
1944
     * @return mixed
1945
     */
1946
    public function getKey()
1947
    {
1948
        return $this->getAttribute($this->getKeyName());
1949
    }
1950
 
1951
    /**
1952
     * Get the queueable identity for the entity.
1953
     *
1954
     * @return mixed
1955
     */
1956
    public function getQueueableId()
1957
    {
1958
        return $this->getKey();
1959
    }
1960
 
1961
    /**
1962
     * Get the queueable relationships for the entity.
1963
     *
1964
     * @return array
1965
     */
1966
    public function getQueueableRelations()
1967
    {
1968
        $relations = [];
1969
 
1970
        foreach ($this->getRelations() as $key => $relation) {
1971
            if (! method_exists($this, $key)) {
1972
                continue;
1973
            }
1974
 
1975
            $relations[] = $key;
1976
 
1977
            if ($relation instanceof QueueableCollection) {
1978
                foreach ($relation->getQueueableRelations() as $collectionValue) {
1979
                    $relations[] = $key.'.'.$collectionValue;
1980
                }
1981
            }
1982
 
1983
            if ($relation instanceof QueueableEntity) {
1984
                foreach ($relation->getQueueableRelations() as $entityValue) {
1985
                    $relations[] = $key.'.'.$entityValue;
1986
                }
1987
            }
1988
        }
1989
 
1990
        return array_unique($relations);
1991
    }
1992
 
1993
    /**
1994
     * Get the queueable connection for the entity.
1995
     *
1996
     * @return string|null
1997
     */
1998
    public function getQueueableConnection()
1999
    {
2000
        return $this->getConnectionName();
2001
    }
2002
 
2003
    /**
2004
     * Get the value of the model's route key.
2005
     *
2006
     * @return mixed
2007
     */
2008
    public function getRouteKey()
2009
    {
2010
        return $this->getAttribute($this->getRouteKeyName());
2011
    }
2012
 
2013
    /**
2014
     * Get the route key for the model.
2015
     *
2016
     * @return string
2017
     */
2018
    public function getRouteKeyName()
2019
    {
2020
        return $this->getKeyName();
2021
    }
2022
 
2023
    /**
2024
     * Retrieve the model for a bound value.
2025
     *
2026
     * @param  mixed  $value
2027
     * @param  string|null  $field
2028
     * @return \Illuminate\Database\Eloquent\Model|null
2029
     */
2030
    public function resolveRouteBinding($value, $field = null)
2031
    {
2032
        return $this->resolveRouteBindingQuery($this, $value, $field)->first();
2033
    }
2034
 
2035
    /**
2036
     * Retrieve the model for a bound value.
2037
     *
2038
     * @param  mixed  $value
2039
     * @param  string|null  $field
2040
     * @return \Illuminate\Database\Eloquent\Model|null
2041
     */
2042
    public function resolveSoftDeletableRouteBinding($value, $field = null)
2043
    {
2044
        return $this->resolveRouteBindingQuery($this, $value, $field)->withTrashed()->first();
2045
    }
2046
 
2047
    /**
2048
     * Retrieve the child model for a bound value.
2049
     *
2050
     * @param  string  $childType
2051
     * @param  mixed  $value
2052
     * @param  string|null  $field
2053
     * @return \Illuminate\Database\Eloquent\Model|null
2054
     */
2055
    public function resolveChildRouteBinding($childType, $value, $field)
2056
    {
2057
        return $this->resolveChildRouteBindingQuery($childType, $value, $field)->first();
2058
    }
2059
 
2060
    /**
2061
     * Retrieve the child model for a bound value.
2062
     *
2063
     * @param  string  $childType
2064
     * @param  mixed  $value
2065
     * @param  string|null  $field
2066
     * @return \Illuminate\Database\Eloquent\Model|null
2067
     */
2068
    public function resolveSoftDeletableChildRouteBinding($childType, $value, $field)
2069
    {
2070
        return $this->resolveChildRouteBindingQuery($childType, $value, $field)->withTrashed()->first();
2071
    }
2072
 
2073
    /**
2074
     * Retrieve the child model query for a bound value.
2075
     *
2076
     * @param  string  $childType
2077
     * @param  mixed  $value
2078
     * @param  string|null  $field
2079
     * @return \Illuminate\Database\Eloquent\Relations\Relation
2080
     */
2081
    protected function resolveChildRouteBindingQuery($childType, $value, $field)
2082
    {
2083
        $relationship = $this->{$this->childRouteBindingRelationshipName($childType)}();
2084
 
2085
        $field = $field ?: $relationship->getRelated()->getRouteKeyName();
2086
 
2087
        if ($relationship instanceof HasManyThrough ||
2088
            $relationship instanceof BelongsToMany) {
2089
            $field = $relationship->getRelated()->getTable().'.'.$field;
2090
        }
2091
 
2092
        return $relationship instanceof Model
2093
            ? $relationship->resolveRouteBindingQuery($relationship, $value, $field)
2094
            : $relationship->getRelated()->resolveRouteBindingQuery($relationship, $value, $field);
2095
    }
2096
 
2097
    /**
2098
     * Retrieve the child route model binding relationship name for the given child type.
2099
     *
2100
     * @param  string  $childType
2101
     * @return string
2102
     */
2103
    protected function childRouteBindingRelationshipName($childType)
2104
    {
2105
        return Str::plural(Str::camel($childType));
2106
    }
2107
 
2108
    /**
2109
     * Retrieve the model for a bound value.
2110
     *
2111
     * @param  \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Relations\Relation  $query
2112
     * @param  mixed  $value
2113
     * @param  string|null  $field
2114
     * @return \Illuminate\Database\Eloquent\Relations\Relation
2115
     */
2116
    public function resolveRouteBindingQuery($query, $value, $field = null)
2117
    {
2118
        return $query->where($field ?? $this->getRouteKeyName(), $value);
2119
    }
2120
 
2121
    /**
2122
     * Get the default foreign key name for the model.
2123
     *
2124
     * @return string
2125
     */
2126
    public function getForeignKey()
2127
    {
2128
        return Str::snake(class_basename($this)).'_'.$this->getKeyName();
2129
    }
2130
 
2131
    /**
2132
     * Get the number of models to return per page.
2133
     *
2134
     * @return int
2135
     */
2136
    public function getPerPage()
2137
    {
2138
        return $this->perPage;
2139
    }
2140
 
2141
    /**
2142
     * Set the number of models to return per page.
2143
     *
2144
     * @param  int  $perPage
2145
     * @return $this
2146
     */
2147
    public function setPerPage($perPage)
2148
    {
2149
        $this->perPage = $perPage;
2150
 
2151
        return $this;
2152
    }
2153
 
2154
    /**
2155
     * Determine if lazy loading is disabled.
2156
     *
2157
     * @return bool
2158
     */
2159
    public static function preventsLazyLoading()
2160
    {
2161
        return static::$modelsShouldPreventLazyLoading;
2162
    }
2163
 
2164
    /**
2165
     * Determine if discarding guarded attribute fills is disabled.
2166
     *
2167
     * @return bool
2168
     */
2169
    public static function preventsSilentlyDiscardingAttributes()
2170
    {
2171
        return static::$modelsShouldPreventSilentlyDiscardingAttributes;
2172
    }
2173
 
2174
    /**
2175
     * Determine if accessing missing attributes is disabled.
2176
     *
2177
     * @return bool
2178
     */
2179
    public static function preventsAccessingMissingAttributes()
2180
    {
2181
        return static::$modelsShouldPreventAccessingMissingAttributes;
2182
    }
2183
 
2184
    /**
2185
     * Get the broadcast channel route definition that is associated with the given entity.
2186
     *
2187
     * @return string
2188
     */
2189
    public function broadcastChannelRoute()
2190
    {
2191
        return str_replace('\\', '.', get_class($this)).'.{'.Str::camel(class_basename($this)).'}';
2192
    }
2193
 
2194
    /**
2195
     * Get the broadcast channel name that is associated with the given entity.
2196
     *
2197
     * @return string
2198
     */
2199
    public function broadcastChannel()
2200
    {
2201
        return str_replace('\\', '.', get_class($this)).'.'.$this->getKey();
2202
    }
2203
 
2204
    /**
2205
     * Dynamically retrieve attributes on the model.
2206
     *
2207
     * @param  string  $key
2208
     * @return mixed
2209
     */
2210
    public function __get($key)
2211
    {
2212
        return $this->getAttribute($key);
2213
    }
2214
 
2215
    /**
2216
     * Dynamically set attributes on the model.
2217
     *
2218
     * @param  string  $key
2219
     * @param  mixed  $value
2220
     * @return void
2221
     */
2222
    public function __set($key, $value)
2223
    {
2224
        $this->setAttribute($key, $value);
2225
    }
2226
 
2227
    /**
2228
     * Determine if the given attribute exists.
2229
     *
2230
     * @param  mixed  $offset
2231
     * @return bool
2232
     */
2233
    public function offsetExists($offset): bool
2234
    {
2235
        try {
2236
            return ! is_null($this->getAttribute($offset));
2237
        } catch (MissingAttributeException) {
2238
            return false;
2239
        }
2240
    }
2241
 
2242
    /**
2243
     * Get the value for a given offset.
2244
     *
2245
     * @param  mixed  $offset
2246
     * @return mixed
2247
     */
2248
    public function offsetGet($offset): mixed
2249
    {
2250
        return $this->getAttribute($offset);
2251
    }
2252
 
2253
    /**
2254
     * Set the value for a given offset.
2255
     *
2256
     * @param  mixed  $offset
2257
     * @param  mixed  $value
2258
     * @return void
2259
     */
2260
    public function offsetSet($offset, $value): void
2261
    {
2262
        $this->setAttribute($offset, $value);
2263
    }
2264
 
2265
    /**
2266
     * Unset the value for a given offset.
2267
     *
2268
     * @param  mixed  $offset
2269
     * @return void
2270
     */
2271
    public function offsetUnset($offset): void
2272
    {
2273
        unset($this->attributes[$offset], $this->relations[$offset]);
2274
    }
2275
 
2276
    /**
2277
     * Determine if an attribute or relation exists on the model.
2278
     *
2279
     * @param  string  $key
2280
     * @return bool
2281
     */
2282
    public function __isset($key)
2283
    {
2284
        return $this->offsetExists($key);
2285
    }
2286
 
2287
    /**
2288
     * Unset an attribute on the model.
2289
     *
2290
     * @param  string  $key
2291
     * @return void
2292
     */
2293
    public function __unset($key)
2294
    {
2295
        $this->offsetUnset($key);
2296
    }
2297
 
2298
    /**
2299
     * Handle dynamic method calls into the model.
2300
     *
2301
     * @param  string  $method
2302
     * @param  array  $parameters
2303
     * @return mixed
2304
     */
2305
    public function __call($method, $parameters)
2306
    {
2307
        if (in_array($method, ['increment', 'decrement'])) {
2308
            return $this->$method(...$parameters);
2309
        }
2310
 
2311
        if ($resolver = ($this->relationResolver(static::class, $method))) {
2312
            return $resolver($this);
2313
        }
2314
 
2315
        return $this->forwardCallTo($this->newQuery(), $method, $parameters);
2316
    }
2317
 
2318
    /**
2319
     * Handle dynamic static method calls into the model.
2320
     *
2321
     * @param  string  $method
2322
     * @param  array  $parameters
2323
     * @return mixed
2324
     */
2325
    public static function __callStatic($method, $parameters)
2326
    {
2327
        return (new static)->$method(...$parameters);
2328
    }
2329
 
2330
    /**
2331
     * Convert the model to its string representation.
2332
     *
2333
     * @return string
2334
     */
2335
    public function __toString()
2336
    {
2337
        return $this->escapeWhenCastingToString
2338
            ? e($this->toJson())
2339
            : $this->toJson();
2340
    }
2341
 
2342
    /**
2343
     * Indicate that the object's string representation should be escaped when __toString is invoked.
2344
     *
2345
     * @param  bool  $escape
2346
     * @return $this
2347
     */
2348
    public function escapeWhenCastingToString($escape = true)
2349
    {
2350
        $this->escapeWhenCastingToString = $escape;
2351
 
2352
        return $this;
2353
    }
2354
 
2355
    /**
2356
     * Prepare the object for serialization.
2357
     *
2358
     * @return array
2359
     */
2360
    public function __sleep()
2361
    {
2362
        $this->mergeAttributesFromCachedCasts();
2363
 
2364
        $this->classCastCache = [];
2365
        $this->attributeCastCache = [];
2366
 
2367
        return array_keys(get_object_vars($this));
2368
    }
2369
 
2370
    /**
2371
     * When a model is being unserialized, check if it needs to be booted.
2372
     *
2373
     * @return void
2374
     */
2375
    public function __wakeup()
2376
    {
2377
        $this->bootIfNotBooted();
2378
 
2379
        $this->initializeTraits();
2380
    }
2381
}