Model.php 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504
  1. <?php
  2. namespace Illuminate\Database\Eloquent;
  3. use Exception;
  4. use ArrayAccess;
  5. use JsonSerializable;
  6. use Illuminate\Support\Arr;
  7. use Illuminate\Support\Str;
  8. use Illuminate\Contracts\Support\Jsonable;
  9. use Illuminate\Contracts\Support\Arrayable;
  10. use Illuminate\Contracts\Routing\UrlRoutable;
  11. use Illuminate\Contracts\Queue\QueueableEntity;
  12. use Illuminate\Database\Eloquent\Relations\Pivot;
  13. use Illuminate\Database\Query\Builder as QueryBuilder;
  14. use Illuminate\Database\ConnectionResolverInterface as Resolver;
  15. abstract class Model implements ArrayAccess, Arrayable, Jsonable, JsonSerializable, QueueableEntity, UrlRoutable
  16. {
  17. use Concerns\HasAttributes,
  18. Concerns\HasEvents,
  19. Concerns\HasGlobalScopes,
  20. Concerns\HasRelationships,
  21. Concerns\HasTimestamps,
  22. Concerns\HidesAttributes,
  23. Concerns\GuardsAttributes;
  24. /**
  25. * The connection name for the model.
  26. *
  27. * @var string
  28. */
  29. protected $connection;
  30. /**
  31. * The table associated with the model.
  32. *
  33. * @var string
  34. */
  35. protected $table;
  36. /**
  37. * The primary key for the model.
  38. *
  39. * @var string
  40. */
  41. protected $primaryKey = 'id';
  42. /**
  43. * The "type" of the auto-incrementing ID.
  44. *
  45. * @var string
  46. */
  47. protected $keyType = 'int';
  48. /**
  49. * Indicates if the IDs are auto-incrementing.
  50. *
  51. * @var bool
  52. */
  53. public $incrementing = true;
  54. /**
  55. * The relations to eager load on every query.
  56. *
  57. * @var array
  58. */
  59. protected $with = [];
  60. /**
  61. * The relationship counts that should be eager loaded on every query.
  62. *
  63. * @var array
  64. */
  65. protected $withCount = [];
  66. /**
  67. * The number of models to return for pagination.
  68. *
  69. * @var int
  70. */
  71. protected $perPage = 15;
  72. /**
  73. * Indicates if the model exists.
  74. *
  75. * @var bool
  76. */
  77. public $exists = false;
  78. /**
  79. * Indicates if the model was inserted during the current request lifecycle.
  80. *
  81. * @var bool
  82. */
  83. public $wasRecentlyCreated = false;
  84. /**
  85. * The connection resolver instance.
  86. *
  87. * @var \Illuminate\Database\ConnectionResolverInterface
  88. */
  89. protected static $resolver;
  90. /**
  91. * The event dispatcher instance.
  92. *
  93. * @var \Illuminate\Contracts\Events\Dispatcher
  94. */
  95. protected static $dispatcher;
  96. /**
  97. * The array of booted models.
  98. *
  99. * @var array
  100. */
  101. protected static $booted = [];
  102. /**
  103. * The array of global scopes on the model.
  104. *
  105. * @var array
  106. */
  107. protected static $globalScopes = [];
  108. /**
  109. * The name of the "created at" column.
  110. *
  111. * @var string
  112. */
  113. const CREATED_AT = 'created_at';
  114. /**
  115. * The name of the "updated at" column.
  116. *
  117. * @var string
  118. */
  119. const UPDATED_AT = 'updated_at';
  120. /**
  121. * Create a new Eloquent model instance.
  122. *
  123. * @param array $attributes
  124. * @return void
  125. */
  126. public function __construct(array $attributes = [])
  127. {
  128. $this->bootIfNotBooted();
  129. $this->syncOriginal();
  130. $this->fill($attributes);
  131. }
  132. /**
  133. * Check if the model needs to be booted and if so, do it.
  134. *
  135. * @return void
  136. */
  137. protected function bootIfNotBooted()
  138. {
  139. if (! isset(static::$booted[static::class])) {
  140. static::$booted[static::class] = true;
  141. $this->fireModelEvent('booting', false);
  142. static::boot();
  143. $this->fireModelEvent('booted', false);
  144. }
  145. }
  146. /**
  147. * The "booting" method of the model.
  148. *
  149. * @return void
  150. */
  151. protected static function boot()
  152. {
  153. static::bootTraits();
  154. }
  155. /**
  156. * Boot all of the bootable traits on the model.
  157. *
  158. * @return void
  159. */
  160. protected static function bootTraits()
  161. {
  162. $class = static::class;
  163. foreach (class_uses_recursive($class) as $trait) {
  164. if (method_exists($class, $method = 'boot'.class_basename($trait))) {
  165. forward_static_call([$class, $method]);
  166. }
  167. }
  168. }
  169. /**
  170. * Clear the list of booted models so they will be re-booted.
  171. *
  172. * @return void
  173. */
  174. public static function clearBootedModels()
  175. {
  176. static::$booted = [];
  177. static::$globalScopes = [];
  178. }
  179. /**
  180. * Fill the model with an array of attributes.
  181. *
  182. * @param array $attributes
  183. * @return $this
  184. *
  185. * @throws \Illuminate\Database\Eloquent\MassAssignmentException
  186. */
  187. public function fill(array $attributes)
  188. {
  189. $totallyGuarded = $this->totallyGuarded();
  190. foreach ($this->fillableFromArray($attributes) as $key => $value) {
  191. $key = $this->removeTableFromKey($key);
  192. // The developers may choose to place some attributes in the "fillable" array
  193. // which means only those attributes may be set through mass assignment to
  194. // the model, and all others will just get ignored for security reasons.
  195. if ($this->isFillable($key)) {
  196. $this->setAttribute($key, $value);
  197. } elseif ($totallyGuarded) {
  198. throw new MassAssignmentException($key);
  199. }
  200. }
  201. return $this;
  202. }
  203. /**
  204. * Fill the model with an array of attributes. Force mass assignment.
  205. *
  206. * @param array $attributes
  207. * @return $this
  208. */
  209. public function forceFill(array $attributes)
  210. {
  211. return static::unguarded(function () use ($attributes) {
  212. return $this->fill($attributes);
  213. });
  214. }
  215. /**
  216. * Qualify the given column name by the model's table.
  217. *
  218. * @param string $column
  219. * @return string
  220. */
  221. public function qualifyColumn($column)
  222. {
  223. if (Str::contains($column, '.')) {
  224. return $column;
  225. }
  226. return $this->getTable().'.'.$column;
  227. }
  228. /**
  229. * Remove the table name from a given key.
  230. *
  231. * @param string $key
  232. * @return string
  233. */
  234. protected function removeTableFromKey($key)
  235. {
  236. return Str::contains($key, '.') ? last(explode('.', $key)) : $key;
  237. }
  238. /**
  239. * Create a new instance of the given model.
  240. *
  241. * @param array $attributes
  242. * @param bool $exists
  243. * @return static
  244. */
  245. public function newInstance($attributes = [], $exists = false)
  246. {
  247. // This method just provides a convenient way for us to generate fresh model
  248. // instances of this current model. It is particularly useful during the
  249. // hydration of new objects via the Eloquent query builder instances.
  250. $model = new static((array) $attributes);
  251. $model->exists = $exists;
  252. $model->setConnection(
  253. $this->getConnectionName()
  254. );
  255. return $model;
  256. }
  257. /**
  258. * Create a new model instance that is existing.
  259. *
  260. * @param array $attributes
  261. * @param string|null $connection
  262. * @return static
  263. */
  264. public function newFromBuilder($attributes = [], $connection = null)
  265. {
  266. $model = $this->newInstance([], true);
  267. $model->setRawAttributes((array) $attributes, true);
  268. $model->setConnection($connection ?: $this->getConnectionName());
  269. $model->fireModelEvent('retrieved', false);
  270. return $model;
  271. }
  272. /**
  273. * Begin querying the model on a given connection.
  274. *
  275. * @param string|null $connection
  276. * @return \Illuminate\Database\Eloquent\Builder
  277. */
  278. public static function on($connection = null)
  279. {
  280. // First we will just create a fresh instance of this model, and then we can
  281. // set the connection on the model so that it is be used for the queries
  282. // we execute, as well as being set on each relationship we retrieve.
  283. $instance = new static;
  284. $instance->setConnection($connection);
  285. return $instance->newQuery();
  286. }
  287. /**
  288. * Begin querying the model on the write connection.
  289. *
  290. * @return \Illuminate\Database\Query\Builder
  291. */
  292. public static function onWriteConnection()
  293. {
  294. $instance = new static;
  295. return $instance->newQuery()->useWritePdo();
  296. }
  297. /**
  298. * Get all of the models from the database.
  299. *
  300. * @param array|mixed $columns
  301. * @return \Illuminate\Database\Eloquent\Collection|static[]
  302. */
  303. public static function all($columns = ['*'])
  304. {
  305. return (new static)->newQuery()->get(
  306. is_array($columns) ? $columns : func_get_args()
  307. );
  308. }
  309. /**
  310. * Begin querying a model with eager loading.
  311. *
  312. * @param array|string $relations
  313. * @return \Illuminate\Database\Eloquent\Builder|static
  314. */
  315. public static function with($relations)
  316. {
  317. return (new static)->newQuery()->with(
  318. is_string($relations) ? func_get_args() : $relations
  319. );
  320. }
  321. /**
  322. * Eager load relations on the model.
  323. *
  324. * @param array|string $relations
  325. * @return $this
  326. */
  327. public function load($relations)
  328. {
  329. $query = $this->newQueryWithoutRelationships()->with(
  330. is_string($relations) ? func_get_args() : $relations
  331. );
  332. $query->eagerLoadRelations([$this]);
  333. return $this;
  334. }
  335. /**
  336. * Eager load relations on the model if they are not already eager loaded.
  337. *
  338. * @param array|string $relations
  339. * @return $this
  340. */
  341. public function loadMissing($relations)
  342. {
  343. $relations = is_string($relations) ? func_get_args() : $relations;
  344. return $this->load(array_filter($relations, function ($relation) {
  345. return ! $this->relationLoaded($relation);
  346. }));
  347. }
  348. /**
  349. * Increment a column's value by a given amount.
  350. *
  351. * @param string $column
  352. * @param int $amount
  353. * @param array $extra
  354. * @return int
  355. */
  356. protected function increment($column, $amount = 1, array $extra = [])
  357. {
  358. return $this->incrementOrDecrement($column, $amount, $extra, 'increment');
  359. }
  360. /**
  361. * Decrement a column's value by a given amount.
  362. *
  363. * @param string $column
  364. * @param int $amount
  365. * @param array $extra
  366. * @return int
  367. */
  368. protected function decrement($column, $amount = 1, array $extra = [])
  369. {
  370. return $this->incrementOrDecrement($column, $amount, $extra, 'decrement');
  371. }
  372. /**
  373. * Run the increment or decrement method on the model.
  374. *
  375. * @param string $column
  376. * @param int $amount
  377. * @param array $extra
  378. * @param string $method
  379. * @return int
  380. */
  381. protected function incrementOrDecrement($column, $amount, $extra, $method)
  382. {
  383. $query = $this->newQuery();
  384. if (! $this->exists) {
  385. return $query->{$method}($column, $amount, $extra);
  386. }
  387. $this->incrementOrDecrementAttributeValue($column, $amount, $extra, $method);
  388. return $query->where(
  389. $this->getKeyName(), $this->getKey()
  390. )->{$method}($column, $amount, $extra);
  391. }
  392. /**
  393. * Increment the underlying attribute value and sync with original.
  394. *
  395. * @param string $column
  396. * @param int $amount
  397. * @param array $extra
  398. * @param string $method
  399. * @return void
  400. */
  401. protected function incrementOrDecrementAttributeValue($column, $amount, $extra, $method)
  402. {
  403. $this->{$column} = $this->{$column} + ($method == 'increment' ? $amount : $amount * -1);
  404. $this->forceFill($extra);
  405. $this->syncOriginalAttribute($column);
  406. }
  407. /**
  408. * Update the model in the database.
  409. *
  410. * @param array $attributes
  411. * @param array $options
  412. * @return bool
  413. */
  414. public function update(array $attributes = [], array $options = [])
  415. {
  416. if (! $this->exists) {
  417. return false;
  418. }
  419. return $this->fill($attributes)->save($options);
  420. }
  421. /**
  422. * Save the model and all of its relationships.
  423. *
  424. * @return bool
  425. */
  426. public function push()
  427. {
  428. if (! $this->save()) {
  429. return false;
  430. }
  431. // To sync all of the relationships to the database, we will simply spin through
  432. // the relationships and save each model via this "push" method, which allows
  433. // us to recurse into all of these nested relations for the model instance.
  434. foreach ($this->relations as $models) {
  435. $models = $models instanceof Collection
  436. ? $models->all() : [$models];
  437. foreach (array_filter($models) as $model) {
  438. if (! $model->push()) {
  439. return false;
  440. }
  441. }
  442. }
  443. return true;
  444. }
  445. /**
  446. * Save the model to the database.
  447. *
  448. * @param array $options
  449. * @return bool
  450. */
  451. public function save(array $options = [])
  452. {
  453. $query = $this->newQueryWithoutScopes();
  454. // If the "saving" event returns false we'll bail out of the save and return
  455. // false, indicating that the save failed. This provides a chance for any
  456. // listeners to cancel save operations if validations fail or whatever.
  457. if ($this->fireModelEvent('saving') === false) {
  458. return false;
  459. }
  460. // If the model already exists in the database we can just update our record
  461. // that is already in this database using the current IDs in this "where"
  462. // clause to only update this model. Otherwise, we'll just insert them.
  463. if ($this->exists) {
  464. $saved = $this->isDirty() ?
  465. $this->performUpdate($query) : true;
  466. }
  467. // If the model is brand new, we'll insert it into our database and set the
  468. // ID attribute on the model to the value of the newly inserted row's ID
  469. // which is typically an auto-increment value managed by the database.
  470. else {
  471. $saved = $this->performInsert($query);
  472. if (! $this->getConnectionName() &&
  473. $connection = $query->getConnection()) {
  474. $this->setConnection($connection->getName());
  475. }
  476. }
  477. // If the model is successfully saved, we need to do a few more things once
  478. // that is done. We will call the "saved" method here to run any actions
  479. // we need to happen after a model gets successfully saved right here.
  480. if ($saved) {
  481. $this->finishSave($options);
  482. }
  483. return $saved;
  484. }
  485. /**
  486. * Save the model to the database using transaction.
  487. *
  488. * @param array $options
  489. * @return bool
  490. *
  491. * @throws \Throwable
  492. */
  493. public function saveOrFail(array $options = [])
  494. {
  495. return $this->getConnection()->transaction(function () use ($options) {
  496. return $this->save($options);
  497. });
  498. }
  499. /**
  500. * Perform any actions that are necessary after the model is saved.
  501. *
  502. * @param array $options
  503. * @return void
  504. */
  505. protected function finishSave(array $options)
  506. {
  507. $this->fireModelEvent('saved', false);
  508. if ($this->isDirty() && ($options['touch'] ?? true)) {
  509. $this->touchOwners();
  510. }
  511. $this->syncOriginal();
  512. }
  513. /**
  514. * Perform a model update operation.
  515. *
  516. * @param \Illuminate\Database\Eloquent\Builder $query
  517. * @return bool
  518. */
  519. protected function performUpdate(Builder $query)
  520. {
  521. // If the updating event returns false, we will cancel the update operation so
  522. // developers can hook Validation systems into their models and cancel this
  523. // operation if the model does not pass validation. Otherwise, we update.
  524. if ($this->fireModelEvent('updating') === false) {
  525. return false;
  526. }
  527. // First we need to create a fresh query instance and touch the creation and
  528. // update timestamp on the model which are maintained by us for developer
  529. // convenience. Then we will just continue saving the model instances.
  530. if ($this->usesTimestamps()) {
  531. $this->updateTimestamps();
  532. }
  533. // Once we have run the update operation, we will fire the "updated" event for
  534. // this model instance. This will allow developers to hook into these after
  535. // models are updated, giving them a chance to do any special processing.
  536. $dirty = $this->getDirty();
  537. if (count($dirty) > 0) {
  538. $this->setKeysForSaveQuery($query)->update($dirty);
  539. $this->fireModelEvent('updated', false);
  540. $this->syncChanges();
  541. }
  542. return true;
  543. }
  544. /**
  545. * Set the keys for a save update query.
  546. *
  547. * @param \Illuminate\Database\Eloquent\Builder $query
  548. * @return \Illuminate\Database\Eloquent\Builder
  549. */
  550. protected function setKeysForSaveQuery(Builder $query)
  551. {
  552. $query->where($this->getKeyName(), '=', $this->getKeyForSaveQuery());
  553. return $query;
  554. }
  555. /**
  556. * Get the primary key value for a save query.
  557. *
  558. * @return mixed
  559. */
  560. protected function getKeyForSaveQuery()
  561. {
  562. return $this->original[$this->getKeyName()]
  563. ?? $this->getKey();
  564. }
  565. /**
  566. * Perform a model insert operation.
  567. *
  568. * @param \Illuminate\Database\Eloquent\Builder $query
  569. * @return bool
  570. */
  571. protected function performInsert(Builder $query)
  572. {
  573. if ($this->fireModelEvent('creating') === false) {
  574. return false;
  575. }
  576. // First we'll need to create a fresh query instance and touch the creation and
  577. // update timestamps on this model, which are maintained by us for developer
  578. // convenience. After, we will just continue saving these model instances.
  579. if ($this->usesTimestamps()) {
  580. $this->updateTimestamps();
  581. }
  582. // If the model has an incrementing key, we can use the "insertGetId" method on
  583. // the query builder, which will give us back the final inserted ID for this
  584. // table from the database. Not all tables have to be incrementing though.
  585. $attributes = $this->attributes;
  586. if ($this->getIncrementing()) {
  587. $this->insertAndSetId($query, $attributes);
  588. }
  589. // If the table isn't incrementing we'll simply insert these attributes as they
  590. // are. These attribute arrays must contain an "id" column previously placed
  591. // there by the developer as the manually determined key for these models.
  592. else {
  593. if (empty($attributes)) {
  594. return true;
  595. }
  596. $query->insert($attributes);
  597. }
  598. // We will go ahead and set the exists property to true, so that it is set when
  599. // the created event is fired, just in case the developer tries to update it
  600. // during the event. This will allow them to do so and run an update here.
  601. $this->exists = true;
  602. $this->wasRecentlyCreated = true;
  603. $this->fireModelEvent('created', false);
  604. return true;
  605. }
  606. /**
  607. * Insert the given attributes and set the ID on the model.
  608. *
  609. * @param \Illuminate\Database\Eloquent\Builder $query
  610. * @param array $attributes
  611. * @return void
  612. */
  613. protected function insertAndSetId(Builder $query, $attributes)
  614. {
  615. $id = $query->insertGetId($attributes, $keyName = $this->getKeyName());
  616. $this->setAttribute($keyName, $id);
  617. }
  618. /**
  619. * Destroy the models for the given IDs.
  620. *
  621. * @param array|int $ids
  622. * @return int
  623. */
  624. public static function destroy($ids)
  625. {
  626. // We'll initialize a count here so we will return the total number of deletes
  627. // for the operation. The developers can then check this number as a boolean
  628. // type value or get this total count of records deleted for logging, etc.
  629. $count = 0;
  630. $ids = is_array($ids) ? $ids : func_get_args();
  631. // We will actually pull the models from the database table and call delete on
  632. // each of them individually so that their events get fired properly with a
  633. // correct set of attributes in case the developers wants to check these.
  634. $key = ($instance = new static)->getKeyName();
  635. foreach ($instance->whereIn($key, $ids)->get() as $model) {
  636. if ($model->delete()) {
  637. $count++;
  638. }
  639. }
  640. return $count;
  641. }
  642. /**
  643. * Delete the model from the database.
  644. *
  645. * @return bool|null
  646. *
  647. * @throws \Exception
  648. */
  649. public function delete()
  650. {
  651. if (is_null($this->getKeyName())) {
  652. throw new Exception('No primary key defined on model.');
  653. }
  654. // If the model doesn't exist, there is nothing to delete so we'll just return
  655. // immediately and not do anything else. Otherwise, we will continue with a
  656. // deletion process on the model, firing the proper events, and so forth.
  657. if (! $this->exists) {
  658. return;
  659. }
  660. if ($this->fireModelEvent('deleting') === false) {
  661. return false;
  662. }
  663. // Here, we'll touch the owning models, verifying these timestamps get updated
  664. // for the models. This will allow any caching to get broken on the parents
  665. // by the timestamp. Then we will go ahead and delete the model instance.
  666. $this->touchOwners();
  667. $this->performDeleteOnModel();
  668. // Once the model has been deleted, we will fire off the deleted event so that
  669. // the developers may hook into post-delete operations. We will then return
  670. // a boolean true as the delete is presumably successful on the database.
  671. $this->fireModelEvent('deleted', false);
  672. return true;
  673. }
  674. /**
  675. * Force a hard delete on a soft deleted model.
  676. *
  677. * This method protects developers from running forceDelete when trait is missing.
  678. *
  679. * @return bool|null
  680. */
  681. public function forceDelete()
  682. {
  683. return $this->delete();
  684. }
  685. /**
  686. * Perform the actual delete query on this model instance.
  687. *
  688. * @return void
  689. */
  690. protected function performDeleteOnModel()
  691. {
  692. $this->setKeysForSaveQuery($this->newQueryWithoutScopes())->delete();
  693. $this->exists = false;
  694. }
  695. /**
  696. * Begin querying the model.
  697. *
  698. * @return \Illuminate\Database\Eloquent\Builder
  699. */
  700. public static function query()
  701. {
  702. return (new static)->newQuery();
  703. }
  704. /**
  705. * Get a new query builder for the model's table.
  706. *
  707. * @return \Illuminate\Database\Eloquent\Builder
  708. */
  709. public function newQuery()
  710. {
  711. return $this->registerGlobalScopes($this->newQueryWithoutScopes());
  712. }
  713. /**
  714. * Get a new query builder with no relationships loaded.
  715. *
  716. * @return \Illuminate\Database\Eloquent\Builder
  717. */
  718. public function newQueryWithoutRelationships()
  719. {
  720. return $this->registerGlobalScopes(
  721. $this->newEloquentBuilder($this->newBaseQueryBuilder())->setModel($this)
  722. );
  723. }
  724. /**
  725. * Register the global scopes for this builder instance.
  726. *
  727. * @param \Illuminate\Database\Eloquent\Builder $builder
  728. * @return \Illuminate\Database\Eloquent\Builder
  729. */
  730. public function registerGlobalScopes($builder)
  731. {
  732. foreach ($this->getGlobalScopes() as $identifier => $scope) {
  733. $builder->withGlobalScope($identifier, $scope);
  734. }
  735. return $builder;
  736. }
  737. /**
  738. * Get a new query builder that doesn't have any global scopes.
  739. *
  740. * @return \Illuminate\Database\Eloquent\Builder|static
  741. */
  742. public function newQueryWithoutScopes()
  743. {
  744. $builder = $this->newEloquentBuilder($this->newBaseQueryBuilder());
  745. // Once we have the query builders, we will set the model instances so the
  746. // builder can easily access any information it may need from the model
  747. // while it is constructing and executing various queries against it.
  748. return $builder->setModel($this)
  749. ->with($this->with)
  750. ->withCount($this->withCount);
  751. }
  752. /**
  753. * Get a new query instance without a given scope.
  754. *
  755. * @param \Illuminate\Database\Eloquent\Scope|string $scope
  756. * @return \Illuminate\Database\Eloquent\Builder
  757. */
  758. public function newQueryWithoutScope($scope)
  759. {
  760. $builder = $this->newQuery();
  761. return $builder->withoutGlobalScope($scope);
  762. }
  763. /**
  764. * Get a new query to restore one or more models by their queueable IDs.
  765. *
  766. * @param array|int $ids
  767. * @return \Illuminate\Database\Eloquent\Builder
  768. */
  769. public function newQueryForRestoration($ids)
  770. {
  771. if (is_array($ids)) {
  772. return $this->newQueryWithoutScopes()->whereIn($this->getQualifiedKeyName(), $ids);
  773. }
  774. return $this->newQueryWithoutScopes()->whereKey($ids);
  775. }
  776. /**
  777. * Create a new Eloquent query builder for the model.
  778. *
  779. * @param \Illuminate\Database\Query\Builder $query
  780. * @return \Illuminate\Database\Eloquent\Builder|static
  781. */
  782. public function newEloquentBuilder($query)
  783. {
  784. return new Builder($query);
  785. }
  786. /**
  787. * Get a new query builder instance for the connection.
  788. *
  789. * @return \Illuminate\Database\Query\Builder
  790. */
  791. protected function newBaseQueryBuilder()
  792. {
  793. $connection = $this->getConnection();
  794. return new QueryBuilder(
  795. $connection, $connection->getQueryGrammar(), $connection->getPostProcessor()
  796. );
  797. }
  798. /**
  799. * Create a new Eloquent Collection instance.
  800. *
  801. * @param array $models
  802. * @return \Illuminate\Database\Eloquent\Collection
  803. */
  804. public function newCollection(array $models = [])
  805. {
  806. return new Collection($models);
  807. }
  808. /**
  809. * Create a new pivot model instance.
  810. *
  811. * @param \Illuminate\Database\Eloquent\Model $parent
  812. * @param array $attributes
  813. * @param string $table
  814. * @param bool $exists
  815. * @param string|null $using
  816. * @return \Illuminate\Database\Eloquent\Relations\Pivot
  817. */
  818. public function newPivot(self $parent, array $attributes, $table, $exists, $using = null)
  819. {
  820. return $using ? $using::fromRawAttributes($parent, $attributes, $table, $exists)
  821. : Pivot::fromAttributes($parent, $attributes, $table, $exists);
  822. }
  823. /**
  824. * Convert the model instance to an array.
  825. *
  826. * @return array
  827. */
  828. public function toArray()
  829. {
  830. return array_merge($this->attributesToArray(), $this->relationsToArray());
  831. }
  832. /**
  833. * Convert the model instance to JSON.
  834. *
  835. * @param int $options
  836. * @return string
  837. *
  838. * @throws \Illuminate\Database\Eloquent\JsonEncodingException
  839. */
  840. public function toJson($options = 0)
  841. {
  842. $json = json_encode($this->jsonSerialize(), $options);
  843. if (JSON_ERROR_NONE !== json_last_error()) {
  844. throw JsonEncodingException::forModel($this, json_last_error_msg());
  845. }
  846. return $json;
  847. }
  848. /**
  849. * Convert the object into something JSON serializable.
  850. *
  851. * @return array
  852. */
  853. public function jsonSerialize()
  854. {
  855. return $this->toArray();
  856. }
  857. /**
  858. * Reload a fresh model instance from the database.
  859. *
  860. * @param array|string $with
  861. * @return static|null
  862. */
  863. public function fresh($with = [])
  864. {
  865. if (! $this->exists) {
  866. return;
  867. }
  868. return static::newQueryWithoutScopes()
  869. ->with(is_string($with) ? func_get_args() : $with)
  870. ->where($this->getKeyName(), $this->getKey())
  871. ->first();
  872. }
  873. /**
  874. * Reload the current model instance with fresh attributes from the database.
  875. *
  876. * @return $this
  877. */
  878. public function refresh()
  879. {
  880. if (! $this->exists) {
  881. return $this;
  882. }
  883. $this->setRawAttributes(
  884. static::newQueryWithoutScopes()->findOrFail($this->getKey())->attributes
  885. );
  886. $this->load(collect($this->relations)->except('pivot')->keys()->toArray());
  887. return $this;
  888. }
  889. /**
  890. * Clone the model into a new, non-existing instance.
  891. *
  892. * @param array|null $except
  893. * @return \Illuminate\Database\Eloquent\Model
  894. */
  895. public function replicate(array $except = null)
  896. {
  897. $defaults = [
  898. $this->getKeyName(),
  899. $this->getCreatedAtColumn(),
  900. $this->getUpdatedAtColumn(),
  901. ];
  902. $attributes = Arr::except(
  903. $this->attributes, $except ? array_unique(array_merge($except, $defaults)) : $defaults
  904. );
  905. return tap(new static, function ($instance) use ($attributes) {
  906. $instance->setRawAttributes($attributes);
  907. $instance->setRelations($this->relations);
  908. });
  909. }
  910. /**
  911. * Determine if two models have the same ID and belong to the same table.
  912. *
  913. * @param \Illuminate\Database\Eloquent\Model|null $model
  914. * @return bool
  915. */
  916. public function is($model)
  917. {
  918. return ! is_null($model) &&
  919. $this->getKey() === $model->getKey() &&
  920. $this->getTable() === $model->getTable() &&
  921. $this->getConnectionName() === $model->getConnectionName();
  922. }
  923. /**
  924. * Determine if two models are not the same.
  925. *
  926. * @param \Illuminate\Database\Eloquent\Model|null $model
  927. * @return bool
  928. */
  929. public function isNot($model)
  930. {
  931. return ! $this->is($model);
  932. }
  933. /**
  934. * Get the database connection for the model.
  935. *
  936. * @return \Illuminate\Database\Connection
  937. */
  938. public function getConnection()
  939. {
  940. return static::resolveConnection($this->getConnectionName());
  941. }
  942. /**
  943. * Get the current connection name for the model.
  944. *
  945. * @return string
  946. */
  947. public function getConnectionName()
  948. {
  949. return $this->connection;
  950. }
  951. /**
  952. * Set the connection associated with the model.
  953. *
  954. * @param string $name
  955. * @return $this
  956. */
  957. public function setConnection($name)
  958. {
  959. $this->connection = $name;
  960. return $this;
  961. }
  962. /**
  963. * Resolve a connection instance.
  964. *
  965. * @param string|null $connection
  966. * @return \Illuminate\Database\Connection
  967. */
  968. public static function resolveConnection($connection = null)
  969. {
  970. return static::$resolver->connection($connection);
  971. }
  972. /**
  973. * Get the connection resolver instance.
  974. *
  975. * @return \Illuminate\Database\ConnectionResolverInterface
  976. */
  977. public static function getConnectionResolver()
  978. {
  979. return static::$resolver;
  980. }
  981. /**
  982. * Set the connection resolver instance.
  983. *
  984. * @param \Illuminate\Database\ConnectionResolverInterface $resolver
  985. * @return void
  986. */
  987. public static function setConnectionResolver(Resolver $resolver)
  988. {
  989. static::$resolver = $resolver;
  990. }
  991. /**
  992. * Unset the connection resolver for models.
  993. *
  994. * @return void
  995. */
  996. public static function unsetConnectionResolver()
  997. {
  998. static::$resolver = null;
  999. }
  1000. /**
  1001. * Get the table associated with the model.
  1002. *
  1003. * @return string
  1004. */
  1005. public function getTable()
  1006. {
  1007. if (! isset($this->table)) {
  1008. return str_replace(
  1009. '\\', '', Str::snake(Str::plural(class_basename($this)))
  1010. );
  1011. }
  1012. return $this->table;
  1013. }
  1014. /**
  1015. * Set the table associated with the model.
  1016. *
  1017. * @param string $table
  1018. * @return $this
  1019. */
  1020. public function setTable($table)
  1021. {
  1022. $this->table = $table;
  1023. return $this;
  1024. }
  1025. /**
  1026. * Get the primary key for the model.
  1027. *
  1028. * @return string
  1029. */
  1030. public function getKeyName()
  1031. {
  1032. return $this->primaryKey;
  1033. }
  1034. /**
  1035. * Set the primary key for the model.
  1036. *
  1037. * @param string $key
  1038. * @return $this
  1039. */
  1040. public function setKeyName($key)
  1041. {
  1042. $this->primaryKey = $key;
  1043. return $this;
  1044. }
  1045. /**
  1046. * Get the table qualified key name.
  1047. *
  1048. * @return string
  1049. */
  1050. public function getQualifiedKeyName()
  1051. {
  1052. return $this->qualifyColumn($this->getKeyName());
  1053. }
  1054. /**
  1055. * Get the auto-incrementing key type.
  1056. *
  1057. * @return string
  1058. */
  1059. public function getKeyType()
  1060. {
  1061. return $this->keyType;
  1062. }
  1063. /**
  1064. * Set the data type for the primary key.
  1065. *
  1066. * @param string $type
  1067. * @return $this
  1068. */
  1069. public function setKeyType($type)
  1070. {
  1071. $this->keyType = $type;
  1072. return $this;
  1073. }
  1074. /**
  1075. * Get the value indicating whether the IDs are incrementing.
  1076. *
  1077. * @return bool
  1078. */
  1079. public function getIncrementing()
  1080. {
  1081. return $this->incrementing;
  1082. }
  1083. /**
  1084. * Set whether IDs are incrementing.
  1085. *
  1086. * @param bool $value
  1087. * @return $this
  1088. */
  1089. public function setIncrementing($value)
  1090. {
  1091. $this->incrementing = $value;
  1092. return $this;
  1093. }
  1094. /**
  1095. * Get the value of the model's primary key.
  1096. *
  1097. * @return mixed
  1098. */
  1099. public function getKey()
  1100. {
  1101. return $this->getAttribute($this->getKeyName());
  1102. }
  1103. /**
  1104. * Get the queueable identity for the entity.
  1105. *
  1106. * @return mixed
  1107. */
  1108. public function getQueueableId()
  1109. {
  1110. return $this->getKey();
  1111. }
  1112. /**
  1113. * Get the queueable connection for the entity.
  1114. *
  1115. * @return mixed
  1116. */
  1117. public function getQueueableConnection()
  1118. {
  1119. return $this->getConnectionName();
  1120. }
  1121. /**
  1122. * Get the value of the model's route key.
  1123. *
  1124. * @return mixed
  1125. */
  1126. public function getRouteKey()
  1127. {
  1128. return $this->getAttribute($this->getRouteKeyName());
  1129. }
  1130. /**
  1131. * Get the route key for the model.
  1132. *
  1133. * @return string
  1134. */
  1135. public function getRouteKeyName()
  1136. {
  1137. return $this->getKeyName();
  1138. }
  1139. /**
  1140. * Retrieve the model for a bound value.
  1141. *
  1142. * @param mixed $value
  1143. * @return \Illuminate\Database\Eloquent\Model|null
  1144. */
  1145. public function resolveRouteBinding($value)
  1146. {
  1147. return $this->where($this->getRouteKeyName(), $value)->first();
  1148. }
  1149. /**
  1150. * Get the default foreign key name for the model.
  1151. *
  1152. * @return string
  1153. */
  1154. public function getForeignKey()
  1155. {
  1156. return Str::snake(class_basename($this)).'_'.$this->primaryKey;
  1157. }
  1158. /**
  1159. * Get the number of models to return per page.
  1160. *
  1161. * @return int
  1162. */
  1163. public function getPerPage()
  1164. {
  1165. return $this->perPage;
  1166. }
  1167. /**
  1168. * Set the number of models to return per page.
  1169. *
  1170. * @param int $perPage
  1171. * @return $this
  1172. */
  1173. public function setPerPage($perPage)
  1174. {
  1175. $this->perPage = $perPage;
  1176. return $this;
  1177. }
  1178. /**
  1179. * Dynamically retrieve attributes on the model.
  1180. *
  1181. * @param string $key
  1182. * @return mixed
  1183. */
  1184. public function __get($key)
  1185. {
  1186. return $this->getAttribute($key);
  1187. }
  1188. /**
  1189. * Dynamically set attributes on the model.
  1190. *
  1191. * @param string $key
  1192. * @param mixed $value
  1193. * @return void
  1194. */
  1195. public function __set($key, $value)
  1196. {
  1197. $this->setAttribute($key, $value);
  1198. }
  1199. /**
  1200. * Determine if the given attribute exists.
  1201. *
  1202. * @param mixed $offset
  1203. * @return bool
  1204. */
  1205. public function offsetExists($offset)
  1206. {
  1207. return ! is_null($this->getAttribute($offset));
  1208. }
  1209. /**
  1210. * Get the value for a given offset.
  1211. *
  1212. * @param mixed $offset
  1213. * @return mixed
  1214. */
  1215. public function offsetGet($offset)
  1216. {
  1217. return $this->getAttribute($offset);
  1218. }
  1219. /**
  1220. * Set the value for a given offset.
  1221. *
  1222. * @param mixed $offset
  1223. * @param mixed $value
  1224. * @return void
  1225. */
  1226. public function offsetSet($offset, $value)
  1227. {
  1228. $this->setAttribute($offset, $value);
  1229. }
  1230. /**
  1231. * Unset the value for a given offset.
  1232. *
  1233. * @param mixed $offset
  1234. * @return void
  1235. */
  1236. public function offsetUnset($offset)
  1237. {
  1238. unset($this->attributes[$offset], $this->relations[$offset]);
  1239. }
  1240. /**
  1241. * Determine if an attribute or relation exists on the model.
  1242. *
  1243. * @param string $key
  1244. * @return bool
  1245. */
  1246. public function __isset($key)
  1247. {
  1248. return $this->offsetExists($key);
  1249. }
  1250. /**
  1251. * Unset an attribute on the model.
  1252. *
  1253. * @param string $key
  1254. * @return void
  1255. */
  1256. public function __unset($key)
  1257. {
  1258. $this->offsetUnset($key);
  1259. }
  1260. /**
  1261. * Handle dynamic method calls into the model.
  1262. *
  1263. * @param string $method
  1264. * @param array $parameters
  1265. * @return mixed
  1266. */
  1267. public function __call($method, $parameters)
  1268. {
  1269. if (in_array($method, ['increment', 'decrement'])) {
  1270. return $this->$method(...$parameters);
  1271. }
  1272. return $this->newQuery()->$method(...$parameters);
  1273. }
  1274. /**
  1275. * Handle dynamic static method calls into the method.
  1276. *
  1277. * @param string $method
  1278. * @param array $parameters
  1279. * @return mixed
  1280. */
  1281. public static function __callStatic($method, $parameters)
  1282. {
  1283. return (new static)->$method(...$parameters);
  1284. }
  1285. /**
  1286. * Convert the model to its string representation.
  1287. *
  1288. * @return string
  1289. */
  1290. public function __toString()
  1291. {
  1292. return $this->toJson();
  1293. }
  1294. /**
  1295. * When a model is being unserialized, check if it needs to be booted.
  1296. *
  1297. * @return void
  1298. */
  1299. public function __wakeup()
  1300. {
  1301. $this->bootIfNotBooted();
  1302. }
  1303. }