You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Model.php 41KB

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