Model.php 39KB

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