Subversion-Projekte lars-tiefland.laravel_shop

Revision

Revision 621 | Details | Vergleich mit vorheriger | 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
    /**
621 lars 1087
     * Save the model and all of its relationships without raising any events to the parent model.
1088
     *
1089
     * @return bool
1090
     */
1091
    public function pushQuietly()
1092
    {
1093
        return static::withoutEvents(fn () => $this->push());
1094
    }
1095
 
1096
    /**
148 lars 1097
     * Save the model to the database without raising any events.
1098
     *
1099
     * @param  array  $options
1100
     * @return bool
1101
     */
1102
    public function saveQuietly(array $options = [])
1103
    {
1104
        return static::withoutEvents(fn () => $this->save($options));
1105
    }
1106
 
1107
    /**
1108
     * Save the model to the database.
1109
     *
1110
     * @param  array  $options
1111
     * @return bool
1112
     */
1113
    public function save(array $options = [])
1114
    {
1115
        $this->mergeAttributesFromCachedCasts();
1116
 
1117
        $query = $this->newModelQuery();
1118
 
1119
        // If the "saving" event returns false we'll bail out of the save and return
1120
        // false, indicating that the save failed. This provides a chance for any
1121
        // listeners to cancel save operations if validations fail or whatever.
1122
        if ($this->fireModelEvent('saving') === false) {
1123
            return false;
1124
        }
1125
 
1126
        // If the model already exists in the database we can just update our record
1127
        // that is already in this database using the current IDs in this "where"
1128
        // clause to only update this model. Otherwise, we'll just insert them.
1129
        if ($this->exists) {
1130
            $saved = $this->isDirty() ?
1131
                $this->performUpdate($query) : true;
1132
        }
1133
 
1134
        // If the model is brand new, we'll insert it into our database and set the
1135
        // ID attribute on the model to the value of the newly inserted row's ID
1136
        // which is typically an auto-increment value managed by the database.
1137
        else {
1138
            $saved = $this->performInsert($query);
1139
 
1140
            if (! $this->getConnectionName() &&
1141
                $connection = $query->getConnection()) {
1142
                $this->setConnection($connection->getName());
1143
            }
1144
        }
1145
 
1146
        // If the model is successfully saved, we need to do a few more things once
1147
        // that is done. We will call the "saved" method here to run any actions
1148
        // we need to happen after a model gets successfully saved right here.
1149
        if ($saved) {
1150
            $this->finishSave($options);
1151
        }
1152
 
1153
        return $saved;
1154
    }
1155
 
1156
    /**
1157
     * Save the model to the database within a transaction.
1158
     *
1159
     * @param  array  $options
1160
     * @return bool
1161
     *
1162
     * @throws \Throwable
1163
     */
1164
    public function saveOrFail(array $options = [])
1165
    {
1166
        return $this->getConnection()->transaction(fn () => $this->save($options));
1167
    }
1168
 
1169
    /**
1170
     * Perform any actions that are necessary after the model is saved.
1171
     *
1172
     * @param  array  $options
1173
     * @return void
1174
     */
1175
    protected function finishSave(array $options)
1176
    {
1177
        $this->fireModelEvent('saved', false);
1178
 
1179
        if ($this->isDirty() && ($options['touch'] ?? true)) {
1180
            $this->touchOwners();
1181
        }
1182
 
1183
        $this->syncOriginal();
1184
    }
1185
 
1186
    /**
1187
     * Perform a model update operation.
1188
     *
1189
     * @param  \Illuminate\Database\Eloquent\Builder  $query
1190
     * @return bool
1191
     */
1192
    protected function performUpdate(Builder $query)
1193
    {
1194
        // If the updating event returns false, we will cancel the update operation so
1195
        // developers can hook Validation systems into their models and cancel this
1196
        // operation if the model does not pass validation. Otherwise, we update.
1197
        if ($this->fireModelEvent('updating') === false) {
1198
            return false;
1199
        }
1200
 
1201
        // First we need to create a fresh query instance and touch the creation and
1202
        // update timestamp on the model which are maintained by us for developer
1203
        // convenience. Then we will just continue saving the model instances.
1204
        if ($this->usesTimestamps()) {
1205
            $this->updateTimestamps();
1206
        }
1207
 
1208
        // Once we have run the update operation, we will fire the "updated" event for
1209
        // this model instance. This will allow developers to hook into these after
1210
        // models are updated, giving them a chance to do any special processing.
1211
        $dirty = $this->getDirty();
1212
 
1213
        if (count($dirty) > 0) {
1214
            $this->setKeysForSaveQuery($query)->update($dirty);
1215
 
1216
            $this->syncChanges();
1217
 
1218
            $this->fireModelEvent('updated', false);
1219
        }
1220
 
1221
        return true;
1222
    }
1223
 
1224
    /**
1225
     * Set the keys for a select query.
1226
     *
1227
     * @param  \Illuminate\Database\Eloquent\Builder  $query
1228
     * @return \Illuminate\Database\Eloquent\Builder
1229
     */
1230
    protected function setKeysForSelectQuery($query)
1231
    {
1232
        $query->where($this->getKeyName(), '=', $this->getKeyForSelectQuery());
1233
 
1234
        return $query;
1235
    }
1236
 
1237
    /**
1238
     * Get the primary key value for a select query.
1239
     *
1240
     * @return mixed
1241
     */
1242
    protected function getKeyForSelectQuery()
1243
    {
1244
        return $this->original[$this->getKeyName()] ?? $this->getKey();
1245
    }
1246
 
1247
    /**
1248
     * Set the keys for a save update query.
1249
     *
1250
     * @param  \Illuminate\Database\Eloquent\Builder  $query
1251
     * @return \Illuminate\Database\Eloquent\Builder
1252
     */
1253
    protected function setKeysForSaveQuery($query)
1254
    {
1255
        $query->where($this->getKeyName(), '=', $this->getKeyForSaveQuery());
1256
 
1257
        return $query;
1258
    }
1259
 
1260
    /**
1261
     * Get the primary key value for a save query.
1262
     *
1263
     * @return mixed
1264
     */
1265
    protected function getKeyForSaveQuery()
1266
    {
1267
        return $this->original[$this->getKeyName()] ?? $this->getKey();
1268
    }
1269
 
1270
    /**
1271
     * Perform a model insert operation.
1272
     *
1273
     * @param  \Illuminate\Database\Eloquent\Builder  $query
1274
     * @return bool
1275
     */
1276
    protected function performInsert(Builder $query)
1277
    {
1278
        if ($this->fireModelEvent('creating') === false) {
1279
            return false;
1280
        }
1281
 
1282
        // First we'll need to create a fresh query instance and touch the creation and
1283
        // update timestamps on this model, which are maintained by us for developer
1284
        // convenience. After, we will just continue saving these model instances.
1285
        if ($this->usesTimestamps()) {
1286
            $this->updateTimestamps();
1287
        }
1288
 
1289
        // If the model has an incrementing key, we can use the "insertGetId" method on
1290
        // the query builder, which will give us back the final inserted ID for this
1291
        // table from the database. Not all tables have to be incrementing though.
1292
        $attributes = $this->getAttributesForInsert();
1293
 
1294
        if ($this->getIncrementing()) {
1295
            $this->insertAndSetId($query, $attributes);
1296
        }
1297
 
1298
        // If the table isn't incrementing we'll simply insert these attributes as they
1299
        // are. These attribute arrays must contain an "id" column previously placed
1300
        // there by the developer as the manually determined key for these models.
1301
        else {
1302
            if (empty($attributes)) {
1303
                return true;
1304
            }
1305
 
1306
            $query->insert($attributes);
1307
        }
1308
 
1309
        // We will go ahead and set the exists property to true, so that it is set when
1310
        // the created event is fired, just in case the developer tries to update it
1311
        // during the event. This will allow them to do so and run an update here.
1312
        $this->exists = true;
1313
 
1314
        $this->wasRecentlyCreated = true;
1315
 
1316
        $this->fireModelEvent('created', false);
1317
 
1318
        return true;
1319
    }
1320
 
1321
    /**
1322
     * Insert the given attributes and set the ID on the model.
1323
     *
1324
     * @param  \Illuminate\Database\Eloquent\Builder  $query
1325
     * @param  array  $attributes
1326
     * @return void
1327
     */
1328
    protected function insertAndSetId(Builder $query, $attributes)
1329
    {
1330
        $id = $query->insertGetId($attributes, $keyName = $this->getKeyName());
1331
 
1332
        $this->setAttribute($keyName, $id);
1333
    }
1334
 
1335
    /**
1336
     * Destroy the models for the given IDs.
1337
     *
1338
     * @param  \Illuminate\Support\Collection|array|int|string  $ids
1339
     * @return int
1340
     */
1341
    public static function destroy($ids)
1342
    {
1343
        if ($ids instanceof EloquentCollection) {
1344
            $ids = $ids->modelKeys();
1345
        }
1346
 
1347
        if ($ids instanceof BaseCollection) {
1348
            $ids = $ids->all();
1349
        }
1350
 
1351
        $ids = is_array($ids) ? $ids : func_get_args();
1352
 
1353
        if (count($ids) === 0) {
1354
            return 0;
1355
        }
1356
 
1357
        // We will actually pull the models from the database table and call delete on
1358
        // each of them individually so that their events get fired properly with a
1359
        // correct set of attributes in case the developers wants to check these.
1360
        $key = ($instance = new static)->getKeyName();
1361
 
1362
        $count = 0;
1363
 
1364
        foreach ($instance->whereIn($key, $ids)->get() as $model) {
1365
            if ($model->delete()) {
1366
                $count++;
1367
            }
1368
        }
1369
 
1370
        return $count;
1371
    }
1372
 
1373
    /**
1374
     * Delete the model from the database.
1375
     *
1376
     * @return bool|null
1377
     *
1378
     * @throws \LogicException
1379
     */
1380
    public function delete()
1381
    {
1382
        $this->mergeAttributesFromCachedCasts();
1383
 
1384
        if (is_null($this->getKeyName())) {
1385
            throw new LogicException('No primary key defined on model.');
1386
        }
1387
 
1388
        // If the model doesn't exist, there is nothing to delete so we'll just return
1389
        // immediately and not do anything else. Otherwise, we will continue with a
1390
        // deletion process on the model, firing the proper events, and so forth.
1391
        if (! $this->exists) {
1392
            return;
1393
        }
1394
 
1395
        if ($this->fireModelEvent('deleting') === false) {
1396
            return false;
1397
        }
1398
 
1399
        // Here, we'll touch the owning models, verifying these timestamps get updated
1400
        // for the models. This will allow any caching to get broken on the parents
1401
        // by the timestamp. Then we will go ahead and delete the model instance.
1402
        $this->touchOwners();
1403
 
1404
        $this->performDeleteOnModel();
1405
 
1406
        // Once the model has been deleted, we will fire off the deleted event so that
1407
        // the developers may hook into post-delete operations. We will then return
1408
        // a boolean true as the delete is presumably successful on the database.
1409
        $this->fireModelEvent('deleted', false);
1410
 
1411
        return true;
1412
    }
1413
 
1414
    /**
1415
     * Delete the model from the database without raising any events.
1416
     *
1417
     * @return bool
1418
     */
1419
    public function deleteQuietly()
1420
    {
1421
        return static::withoutEvents(fn () => $this->delete());
1422
    }
1423
 
1424
    /**
1425
     * Delete the model from the database within a transaction.
1426
     *
1427
     * @return bool|null
1428
     *
1429
     * @throws \Throwable
1430
     */
1431
    public function deleteOrFail()
1432
    {
1433
        if (! $this->exists) {
1434
            return false;
1435
        }
1436
 
1437
        return $this->getConnection()->transaction(fn () => $this->delete());
1438
    }
1439
 
1440
    /**
1441
     * Force a hard delete on a soft deleted model.
1442
     *
1443
     * This method protects developers from running forceDelete when the trait is missing.
1444
     *
1445
     * @return bool|null
1446
     */
1447
    public function forceDelete()
1448
    {
1449
        return $this->delete();
1450
    }
1451
 
1452
    /**
1453
     * Perform the actual delete query on this model instance.
1454
     *
1455
     * @return void
1456
     */
1457
    protected function performDeleteOnModel()
1458
    {
1459
        $this->setKeysForSaveQuery($this->newModelQuery())->delete();
1460
 
1461
        $this->exists = false;
1462
    }
1463
 
1464
    /**
1465
     * Begin querying the model.
1466
     *
1467
     * @return \Illuminate\Database\Eloquent\Builder
1468
     */
1469
    public static function query()
1470
    {
1471
        return (new static)->newQuery();
1472
    }
1473
 
1474
    /**
1475
     * Get a new query builder for the model's table.
1476
     *
1477
     * @return \Illuminate\Database\Eloquent\Builder
1478
     */
1479
    public function newQuery()
1480
    {
1481
        return $this->registerGlobalScopes($this->newQueryWithoutScopes());
1482
    }
1483
 
1484
    /**
1485
     * Get a new query builder that doesn't have any global scopes or eager loading.
1486
     *
1487
     * @return \Illuminate\Database\Eloquent\Builder|static
1488
     */
1489
    public function newModelQuery()
1490
    {
1491
        return $this->newEloquentBuilder(
1492
            $this->newBaseQueryBuilder()
1493
        )->setModel($this);
1494
    }
1495
 
1496
    /**
1497
     * Get a new query builder with no relationships loaded.
1498
     *
1499
     * @return \Illuminate\Database\Eloquent\Builder
1500
     */
1501
    public function newQueryWithoutRelationships()
1502
    {
1503
        return $this->registerGlobalScopes($this->newModelQuery());
1504
    }
1505
 
1506
    /**
1507
     * Register the global scopes for this builder instance.
1508
     *
1509
     * @param  \Illuminate\Database\Eloquent\Builder  $builder
1510
     * @return \Illuminate\Database\Eloquent\Builder
1511
     */
1512
    public function registerGlobalScopes($builder)
1513
    {
1514
        foreach ($this->getGlobalScopes() as $identifier => $scope) {
1515
            $builder->withGlobalScope($identifier, $scope);
1516
        }
1517
 
1518
        return $builder;
1519
    }
1520
 
1521
    /**
1522
     * Get a new query builder that doesn't have any global scopes.
1523
     *
1524
     * @return \Illuminate\Database\Eloquent\Builder|static
1525
     */
1526
    public function newQueryWithoutScopes()
1527
    {
1528
        return $this->newModelQuery()
1529
            ->with($this->with)
1530
            ->withCount($this->withCount);
1531
    }
1532
 
1533
    /**
1534
     * Get a new query instance without a given scope.
1535
     *
1536
     * @param  \Illuminate\Database\Eloquent\Scope|string  $scope
1537
     * @return \Illuminate\Database\Eloquent\Builder
1538
     */
1539
    public function newQueryWithoutScope($scope)
1540
    {
1541
        return $this->newQuery()->withoutGlobalScope($scope);
1542
    }
1543
 
1544
    /**
1545
     * Get a new query to restore one or more models by their queueable IDs.
1546
     *
1547
     * @param  array|int  $ids
1548
     * @return \Illuminate\Database\Eloquent\Builder
1549
     */
1550
    public function newQueryForRestoration($ids)
1551
    {
1552
        return $this->newQueryWithoutScopes()->whereKey($ids);
1553
    }
1554
 
1555
    /**
1556
     * Create a new Eloquent query builder for the model.
1557
     *
1558
     * @param  \Illuminate\Database\Query\Builder  $query
1559
     * @return \Illuminate\Database\Eloquent\Builder|static
1560
     */
1561
    public function newEloquentBuilder($query)
1562
    {
1563
        return new Builder($query);
1564
    }
1565
 
1566
    /**
1567
     * Get a new query builder instance for the connection.
1568
     *
1569
     * @return \Illuminate\Database\Query\Builder
1570
     */
1571
    protected function newBaseQueryBuilder()
1572
    {
1573
        return $this->getConnection()->query();
1574
    }
1575
 
1576
    /**
1577
     * Create a new Eloquent Collection instance.
1578
     *
1579
     * @param  array  $models
1580
     * @return \Illuminate\Database\Eloquent\Collection
1581
     */
1582
    public function newCollection(array $models = [])
1583
    {
1584
        return new Collection($models);
1585
    }
1586
 
1587
    /**
1588
     * Create a new pivot model instance.
1589
     *
1590
     * @param  \Illuminate\Database\Eloquent\Model  $parent
1591
     * @param  array  $attributes
1592
     * @param  string  $table
1593
     * @param  bool  $exists
1594
     * @param  string|null  $using
1595
     * @return \Illuminate\Database\Eloquent\Relations\Pivot
1596
     */
1597
    public function newPivot(self $parent, array $attributes, $table, $exists, $using = null)
1598
    {
1599
        return $using ? $using::fromRawAttributes($parent, $attributes, $table, $exists)
1600
            : Pivot::fromAttributes($parent, $attributes, $table, $exists);
1601
    }
1602
 
1603
    /**
1604
     * Determine if the model has a given scope.
1605
     *
1606
     * @param  string  $scope
1607
     * @return bool
1608
     */
1609
    public function hasNamedScope($scope)
1610
    {
1611
        return method_exists($this, 'scope'.ucfirst($scope));
1612
    }
1613
 
1614
    /**
1615
     * Apply the given named scope if possible.
1616
     *
1617
     * @param  string  $scope
1618
     * @param  array  $parameters
1619
     * @return mixed
1620
     */
1621
    public function callNamedScope($scope, array $parameters = [])
1622
    {
1623
        return $this->{'scope'.ucfirst($scope)}(...$parameters);
1624
    }
1625
 
1626
    /**
1627
     * Convert the model instance to an array.
1628
     *
1629
     * @return array
1630
     */
1631
    public function toArray()
1632
    {
1633
        return array_merge($this->attributesToArray(), $this->relationsToArray());
1634
    }
1635
 
1636
    /**
1637
     * Convert the model instance to JSON.
1638
     *
1639
     * @param  int  $options
1640
     * @return string
1641
     *
1642
     * @throws \Illuminate\Database\Eloquent\JsonEncodingException
1643
     */
1644
    public function toJson($options = 0)
1645
    {
1646
        $json = json_encode($this->jsonSerialize(), $options);
1647
 
1648
        if (json_last_error() !== JSON_ERROR_NONE) {
1649
            throw JsonEncodingException::forModel($this, json_last_error_msg());
1650
        }
1651
 
1652
        return $json;
1653
    }
1654
 
1655
    /**
1656
     * Convert the object into something JSON serializable.
1657
     *
1658
     * @return mixed
1659
     */
1660
    public function jsonSerialize(): mixed
1661
    {
1662
        return $this->toArray();
1663
    }
1664
 
1665
    /**
1666
     * Reload a fresh model instance from the database.
1667
     *
1668
     * @param  array|string  $with
1669
     * @return static|null
1670
     */
1671
    public function fresh($with = [])
1672
    {
1673
        if (! $this->exists) {
1674
            return;
1675
        }
1676
 
1677
        return $this->setKeysForSelectQuery($this->newQueryWithoutScopes())
1678
            ->useWritePdo()
1679
            ->with(is_string($with) ? func_get_args() : $with)
1680
            ->first();
1681
    }
1682
 
1683
    /**
1684
     * Reload the current model instance with fresh attributes from the database.
1685
     *
1686
     * @return $this
1687
     */
1688
    public function refresh()
1689
    {
1690
        if (! $this->exists) {
1691
            return $this;
1692
        }
1693
 
1694
        $this->setRawAttributes(
1695
            $this->setKeysForSelectQuery($this->newQueryWithoutScopes())
1696
                ->useWritePdo()
1697
                ->firstOrFail()
1698
                ->attributes
1699
        );
1700
 
1701
        $this->load(collect($this->relations)->reject(function ($relation) {
1702
            return $relation instanceof Pivot
1703
                || (is_object($relation) && in_array(AsPivot::class, class_uses_recursive($relation), true));
1704
        })->keys()->all());
1705
 
1706
        $this->syncOriginal();
1707
 
1708
        return $this;
1709
    }
1710
 
1711
    /**
1712
     * Clone the model into a new, non-existing instance.
1713
     *
1714
     * @param  array|null  $except
1715
     * @return static
1716
     */
1717
    public function replicate(array $except = null)
1718
    {
1719
        $defaults = array_values(array_filter([
1720
            $this->getKeyName(),
1721
            $this->getCreatedAtColumn(),
1722
            $this->getUpdatedAtColumn(),
1723
        ]));
1724
 
1725
        $attributes = Arr::except(
1726
            $this->getAttributes(), $except ? array_unique(array_merge($except, $defaults)) : $defaults
1727
        );
1728
 
1729
        return tap(new static, function ($instance) use ($attributes) {
1730
            $instance->setRawAttributes($attributes);
1731
 
1732
            $instance->setRelations($this->relations);
1733
 
1734
            $instance->fireModelEvent('replicating', false);
1735
        });
1736
    }
1737
 
1738
    /**
1739
     * Clone the model into a new, non-existing instance without raising any events.
1740
     *
1741
     * @param  array|null  $except
1742
     * @return static
1743
     */
1744
    public function replicateQuietly(array $except = null)
1745
    {
1746
        return static::withoutEvents(fn () => $this->replicate($except));
1747
    }
1748
 
1749
    /**
1750
     * Determine if two models have the same ID and belong to the same table.
1751
     *
1752
     * @param  \Illuminate\Database\Eloquent\Model|null  $model
1753
     * @return bool
1754
     */
1755
    public function is($model)
1756
    {
1757
        return ! is_null($model) &&
1758
            $this->getKey() === $model->getKey() &&
1759
            $this->getTable() === $model->getTable() &&
1760
            $this->getConnectionName() === $model->getConnectionName();
1761
    }
1762
 
1763
    /**
1764
     * Determine if two models are not the same.
1765
     *
1766
     * @param  \Illuminate\Database\Eloquent\Model|null  $model
1767
     * @return bool
1768
     */
1769
    public function isNot($model)
1770
    {
1771
        return ! $this->is($model);
1772
    }
1773
 
1774
    /**
1775
     * Get the database connection for the model.
1776
     *
1777
     * @return \Illuminate\Database\Connection
1778
     */
1779
    public function getConnection()
1780
    {
1781
        return static::resolveConnection($this->getConnectionName());
1782
    }
1783
 
1784
    /**
1785
     * Get the current connection name for the model.
1786
     *
1787
     * @return string|null
1788
     */
1789
    public function getConnectionName()
1790
    {
1791
        return $this->connection;
1792
    }
1793
 
1794
    /**
1795
     * Set the connection associated with the model.
1796
     *
1797
     * @param  string|null  $name
1798
     * @return $this
1799
     */
1800
    public function setConnection($name)
1801
    {
1802
        $this->connection = $name;
1803
 
1804
        return $this;
1805
    }
1806
 
1807
    /**
1808
     * Resolve a connection instance.
1809
     *
1810
     * @param  string|null  $connection
1811
     * @return \Illuminate\Database\Connection
1812
     */
1813
    public static function resolveConnection($connection = null)
1814
    {
1815
        return static::$resolver->connection($connection);
1816
    }
1817
 
1818
    /**
1819
     * Get the connection resolver instance.
1820
     *
1821
     * @return \Illuminate\Database\ConnectionResolverInterface
1822
     */
1823
    public static function getConnectionResolver()
1824
    {
1825
        return static::$resolver;
1826
    }
1827
 
1828
    /**
1829
     * Set the connection resolver instance.
1830
     *
1831
     * @param  \Illuminate\Database\ConnectionResolverInterface  $resolver
1832
     * @return void
1833
     */
1834
    public static function setConnectionResolver(Resolver $resolver)
1835
    {
1836
        static::$resolver = $resolver;
1837
    }
1838
 
1839
    /**
1840
     * Unset the connection resolver for models.
1841
     *
1842
     * @return void
1843
     */
1844
    public static function unsetConnectionResolver()
1845
    {
1846
        static::$resolver = null;
1847
    }
1848
 
1849
    /**
1850
     * Get the table associated with the model.
1851
     *
1852
     * @return string
1853
     */
1854
    public function getTable()
1855
    {
1856
        return $this->table ?? Str::snake(Str::pluralStudly(class_basename($this)));
1857
    }
1858
 
1859
    /**
1860
     * Set the table associated with the model.
1861
     *
1862
     * @param  string  $table
1863
     * @return $this
1864
     */
1865
    public function setTable($table)
1866
    {
1867
        $this->table = $table;
1868
 
1869
        return $this;
1870
    }
1871
 
1872
    /**
1873
     * Get the primary key for the model.
1874
     *
1875
     * @return string
1876
     */
1877
    public function getKeyName()
1878
    {
1879
        return $this->primaryKey;
1880
    }
1881
 
1882
    /**
1883
     * Set the primary key for the model.
1884
     *
1885
     * @param  string  $key
1886
     * @return $this
1887
     */
1888
    public function setKeyName($key)
1889
    {
1890
        $this->primaryKey = $key;
1891
 
1892
        return $this;
1893
    }
1894
 
1895
    /**
1896
     * Get the table qualified key name.
1897
     *
1898
     * @return string
1899
     */
1900
    public function getQualifiedKeyName()
1901
    {
1902
        return $this->qualifyColumn($this->getKeyName());
1903
    }
1904
 
1905
    /**
1906
     * Get the auto-incrementing key type.
1907
     *
1908
     * @return string
1909
     */
1910
    public function getKeyType()
1911
    {
1912
        return $this->keyType;
1913
    }
1914
 
1915
    /**
1916
     * Set the data type for the primary key.
1917
     *
1918
     * @param  string  $type
1919
     * @return $this
1920
     */
1921
    public function setKeyType($type)
1922
    {
1923
        $this->keyType = $type;
1924
 
1925
        return $this;
1926
    }
1927
 
1928
    /**
1929
     * Get the value indicating whether the IDs are incrementing.
1930
     *
1931
     * @return bool
1932
     */
1933
    public function getIncrementing()
1934
    {
1935
        return $this->incrementing;
1936
    }
1937
 
1938
    /**
1939
     * Set whether IDs are incrementing.
1940
     *
1941
     * @param  bool  $value
1942
     * @return $this
1943
     */
1944
    public function setIncrementing($value)
1945
    {
1946
        $this->incrementing = $value;
1947
 
1948
        return $this;
1949
    }
1950
 
1951
    /**
1952
     * Get the value of the model's primary key.
1953
     *
1954
     * @return mixed
1955
     */
1956
    public function getKey()
1957
    {
1958
        return $this->getAttribute($this->getKeyName());
1959
    }
1960
 
1961
    /**
1962
     * Get the queueable identity for the entity.
1963
     *
1964
     * @return mixed
1965
     */
1966
    public function getQueueableId()
1967
    {
1968
        return $this->getKey();
1969
    }
1970
 
1971
    /**
1972
     * Get the queueable relationships for the entity.
1973
     *
1974
     * @return array
1975
     */
1976
    public function getQueueableRelations()
1977
    {
1978
        $relations = [];
1979
 
1980
        foreach ($this->getRelations() as $key => $relation) {
1981
            if (! method_exists($this, $key)) {
1982
                continue;
1983
            }
1984
 
1985
            $relations[] = $key;
1986
 
1987
            if ($relation instanceof QueueableCollection) {
1988
                foreach ($relation->getQueueableRelations() as $collectionValue) {
1989
                    $relations[] = $key.'.'.$collectionValue;
1990
                }
1991
            }
1992
 
1993
            if ($relation instanceof QueueableEntity) {
1994
                foreach ($relation->getQueueableRelations() as $entityValue) {
1995
                    $relations[] = $key.'.'.$entityValue;
1996
                }
1997
            }
1998
        }
1999
 
2000
        return array_unique($relations);
2001
    }
2002
 
2003
    /**
2004
     * Get the queueable connection for the entity.
2005
     *
2006
     * @return string|null
2007
     */
2008
    public function getQueueableConnection()
2009
    {
2010
        return $this->getConnectionName();
2011
    }
2012
 
2013
    /**
2014
     * Get the value of the model's route key.
2015
     *
2016
     * @return mixed
2017
     */
2018
    public function getRouteKey()
2019
    {
2020
        return $this->getAttribute($this->getRouteKeyName());
2021
    }
2022
 
2023
    /**
2024
     * Get the route key for the model.
2025
     *
2026
     * @return string
2027
     */
2028
    public function getRouteKeyName()
2029
    {
2030
        return $this->getKeyName();
2031
    }
2032
 
2033
    /**
2034
     * Retrieve the model for a bound value.
2035
     *
2036
     * @param  mixed  $value
2037
     * @param  string|null  $field
2038
     * @return \Illuminate\Database\Eloquent\Model|null
2039
     */
2040
    public function resolveRouteBinding($value, $field = null)
2041
    {
2042
        return $this->resolveRouteBindingQuery($this, $value, $field)->first();
2043
    }
2044
 
2045
    /**
2046
     * Retrieve the model for a bound value.
2047
     *
2048
     * @param  mixed  $value
2049
     * @param  string|null  $field
2050
     * @return \Illuminate\Database\Eloquent\Model|null
2051
     */
2052
    public function resolveSoftDeletableRouteBinding($value, $field = null)
2053
    {
2054
        return $this->resolveRouteBindingQuery($this, $value, $field)->withTrashed()->first();
2055
    }
2056
 
2057
    /**
2058
     * Retrieve the child model for a bound value.
2059
     *
2060
     * @param  string  $childType
2061
     * @param  mixed  $value
2062
     * @param  string|null  $field
2063
     * @return \Illuminate\Database\Eloquent\Model|null
2064
     */
2065
    public function resolveChildRouteBinding($childType, $value, $field)
2066
    {
2067
        return $this->resolveChildRouteBindingQuery($childType, $value, $field)->first();
2068
    }
2069
 
2070
    /**
2071
     * Retrieve the child model for a bound value.
2072
     *
2073
     * @param  string  $childType
2074
     * @param  mixed  $value
2075
     * @param  string|null  $field
2076
     * @return \Illuminate\Database\Eloquent\Model|null
2077
     */
2078
    public function resolveSoftDeletableChildRouteBinding($childType, $value, $field)
2079
    {
2080
        return $this->resolveChildRouteBindingQuery($childType, $value, $field)->withTrashed()->first();
2081
    }
2082
 
2083
    /**
2084
     * Retrieve the child model query for a bound value.
2085
     *
2086
     * @param  string  $childType
2087
     * @param  mixed  $value
2088
     * @param  string|null  $field
2089
     * @return \Illuminate\Database\Eloquent\Relations\Relation
2090
     */
2091
    protected function resolveChildRouteBindingQuery($childType, $value, $field)
2092
    {
2093
        $relationship = $this->{$this->childRouteBindingRelationshipName($childType)}();
2094
 
2095
        $field = $field ?: $relationship->getRelated()->getRouteKeyName();
2096
 
2097
        if ($relationship instanceof HasManyThrough ||
2098
            $relationship instanceof BelongsToMany) {
2099
            $field = $relationship->getRelated()->getTable().'.'.$field;
2100
        }
2101
 
2102
        return $relationship instanceof Model
2103
            ? $relationship->resolveRouteBindingQuery($relationship, $value, $field)
2104
            : $relationship->getRelated()->resolveRouteBindingQuery($relationship, $value, $field);
2105
    }
2106
 
2107
    /**
2108
     * Retrieve the child route model binding relationship name for the given child type.
2109
     *
2110
     * @param  string  $childType
2111
     * @return string
2112
     */
2113
    protected function childRouteBindingRelationshipName($childType)
2114
    {
2115
        return Str::plural(Str::camel($childType));
2116
    }
2117
 
2118
    /**
2119
     * Retrieve the model for a bound value.
2120
     *
2121
     * @param  \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Relations\Relation  $query
2122
     * @param  mixed  $value
2123
     * @param  string|null  $field
2124
     * @return \Illuminate\Database\Eloquent\Relations\Relation
2125
     */
2126
    public function resolveRouteBindingQuery($query, $value, $field = null)
2127
    {
2128
        return $query->where($field ?? $this->getRouteKeyName(), $value);
2129
    }
2130
 
2131
    /**
2132
     * Get the default foreign key name for the model.
2133
     *
2134
     * @return string
2135
     */
2136
    public function getForeignKey()
2137
    {
2138
        return Str::snake(class_basename($this)).'_'.$this->getKeyName();
2139
    }
2140
 
2141
    /**
2142
     * Get the number of models to return per page.
2143
     *
2144
     * @return int
2145
     */
2146
    public function getPerPage()
2147
    {
2148
        return $this->perPage;
2149
    }
2150
 
2151
    /**
2152
     * Set the number of models to return per page.
2153
     *
2154
     * @param  int  $perPage
2155
     * @return $this
2156
     */
2157
    public function setPerPage($perPage)
2158
    {
2159
        $this->perPage = $perPage;
2160
 
2161
        return $this;
2162
    }
2163
 
2164
    /**
2165
     * Determine if lazy loading is disabled.
2166
     *
2167
     * @return bool
2168
     */
2169
    public static function preventsLazyLoading()
2170
    {
2171
        return static::$modelsShouldPreventLazyLoading;
2172
    }
2173
 
2174
    /**
2175
     * Determine if discarding guarded attribute fills is disabled.
2176
     *
2177
     * @return bool
2178
     */
2179
    public static function preventsSilentlyDiscardingAttributes()
2180
    {
2181
        return static::$modelsShouldPreventSilentlyDiscardingAttributes;
2182
    }
2183
 
2184
    /**
2185
     * Determine if accessing missing attributes is disabled.
2186
     *
2187
     * @return bool
2188
     */
2189
    public static function preventsAccessingMissingAttributes()
2190
    {
2191
        return static::$modelsShouldPreventAccessingMissingAttributes;
2192
    }
2193
 
2194
    /**
2195
     * Get the broadcast channel route definition that is associated with the given entity.
2196
     *
2197
     * @return string
2198
     */
2199
    public function broadcastChannelRoute()
2200
    {
2201
        return str_replace('\\', '.', get_class($this)).'.{'.Str::camel(class_basename($this)).'}';
2202
    }
2203
 
2204
    /**
2205
     * Get the broadcast channel name that is associated with the given entity.
2206
     *
2207
     * @return string
2208
     */
2209
    public function broadcastChannel()
2210
    {
2211
        return str_replace('\\', '.', get_class($this)).'.'.$this->getKey();
2212
    }
2213
 
2214
    /**
2215
     * Dynamically retrieve attributes on the model.
2216
     *
2217
     * @param  string  $key
2218
     * @return mixed
2219
     */
2220
    public function __get($key)
2221
    {
2222
        return $this->getAttribute($key);
2223
    }
2224
 
2225
    /**
2226
     * Dynamically set attributes on the model.
2227
     *
2228
     * @param  string  $key
2229
     * @param  mixed  $value
2230
     * @return void
2231
     */
2232
    public function __set($key, $value)
2233
    {
2234
        $this->setAttribute($key, $value);
2235
    }
2236
 
2237
    /**
2238
     * Determine if the given attribute exists.
2239
     *
2240
     * @param  mixed  $offset
2241
     * @return bool
2242
     */
2243
    public function offsetExists($offset): bool
2244
    {
2245
        try {
2246
            return ! is_null($this->getAttribute($offset));
2247
        } catch (MissingAttributeException) {
2248
            return false;
2249
        }
2250
    }
2251
 
2252
    /**
2253
     * Get the value for a given offset.
2254
     *
2255
     * @param  mixed  $offset
2256
     * @return mixed
2257
     */
2258
    public function offsetGet($offset): mixed
2259
    {
2260
        return $this->getAttribute($offset);
2261
    }
2262
 
2263
    /**
2264
     * Set the value for a given offset.
2265
     *
2266
     * @param  mixed  $offset
2267
     * @param  mixed  $value
2268
     * @return void
2269
     */
2270
    public function offsetSet($offset, $value): void
2271
    {
2272
        $this->setAttribute($offset, $value);
2273
    }
2274
 
2275
    /**
2276
     * Unset the value for a given offset.
2277
     *
2278
     * @param  mixed  $offset
2279
     * @return void
2280
     */
2281
    public function offsetUnset($offset): void
2282
    {
2283
        unset($this->attributes[$offset], $this->relations[$offset]);
2284
    }
2285
 
2286
    /**
2287
     * Determine if an attribute or relation exists on the model.
2288
     *
2289
     * @param  string  $key
2290
     * @return bool
2291
     */
2292
    public function __isset($key)
2293
    {
2294
        return $this->offsetExists($key);
2295
    }
2296
 
2297
    /**
2298
     * Unset an attribute on the model.
2299
     *
2300
     * @param  string  $key
2301
     * @return void
2302
     */
2303
    public function __unset($key)
2304
    {
2305
        $this->offsetUnset($key);
2306
    }
2307
 
2308
    /**
2309
     * Handle dynamic method calls into the model.
2310
     *
2311
     * @param  string  $method
2312
     * @param  array  $parameters
2313
     * @return mixed
2314
     */
2315
    public function __call($method, $parameters)
2316
    {
2317
        if (in_array($method, ['increment', 'decrement'])) {
2318
            return $this->$method(...$parameters);
2319
        }
2320
 
991 lars 2321
        if ($resolver = $this->relationResolver(static::class, $method)) {
148 lars 2322
            return $resolver($this);
2323
        }
2324
 
621 lars 2325
        if (Str::startsWith($method, 'through') &&
2326
            method_exists($this, $relationMethod = Str::of($method)->after('through')->lcfirst()->toString())) {
2327
            return $this->through($relationMethod);
2328
        }
2329
 
148 lars 2330
        return $this->forwardCallTo($this->newQuery(), $method, $parameters);
2331
    }
2332
 
2333
    /**
2334
     * Handle dynamic static method calls into the model.
2335
     *
2336
     * @param  string  $method
2337
     * @param  array  $parameters
2338
     * @return mixed
2339
     */
2340
    public static function __callStatic($method, $parameters)
2341
    {
2342
        return (new static)->$method(...$parameters);
2343
    }
2344
 
2345
    /**
2346
     * Convert the model to its string representation.
2347
     *
2348
     * @return string
2349
     */
2350
    public function __toString()
2351
    {
2352
        return $this->escapeWhenCastingToString
2353
            ? e($this->toJson())
2354
            : $this->toJson();
2355
    }
2356
 
2357
    /**
2358
     * Indicate that the object's string representation should be escaped when __toString is invoked.
2359
     *
2360
     * @param  bool  $escape
2361
     * @return $this
2362
     */
2363
    public function escapeWhenCastingToString($escape = true)
2364
    {
2365
        $this->escapeWhenCastingToString = $escape;
2366
 
2367
        return $this;
2368
    }
2369
 
2370
    /**
2371
     * Prepare the object for serialization.
2372
     *
2373
     * @return array
2374
     */
2375
    public function __sleep()
2376
    {
2377
        $this->mergeAttributesFromCachedCasts();
2378
 
2379
        $this->classCastCache = [];
2380
        $this->attributeCastCache = [];
2381
 
2382
        return array_keys(get_object_vars($this));
2383
    }
2384
 
2385
    /**
2386
     * When a model is being unserialized, check if it needs to be booted.
2387
     *
2388
     * @return void
2389
     */
2390
    public function __wakeup()
2391
    {
2392
        $this->bootIfNotBooted();
2393
 
2394
        $this->initializeTraits();
2395
    }
2396
}