Skip to content

Commit c9b9d2c

Browse files
authored
Merge 4.2 into 4.3 (#2800)
2 parents f2d2820 + 90ebf12 commit c9b9d2c

31 files changed

+2027
-512
lines changed

docs/eloquent-models.txt

Lines changed: 24 additions & 512 deletions
Large diffs are not rendered by default.

docs/eloquent-models/model-class.txt

Lines changed: 317 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,317 @@
1+
.. _laravel-eloquent-model-class:
2+
3+
====================
4+
Eloquent Model Class
5+
====================
6+
7+
.. facet::
8+
:name: genre
9+
:values: reference
10+
11+
.. meta::
12+
:keywords: php framework, odm, code example, authentication, laravel
13+
14+
.. contents:: On this page
15+
:local:
16+
:backlinks: none
17+
:depth: 2
18+
:class: singlecol
19+
20+
Overview
21+
--------
22+
23+
This guide shows you how to use the {+odm-long+} to define and
24+
customize Laravel Eloquent models. You can use these models to work with
25+
MongoDB data by using the Laravel Eloquent object-relational mapper (ORM).
26+
27+
The following sections explain how to add Laravel Eloquent ORM behaviors
28+
to {+odm-short+} models:
29+
30+
- :ref:`laravel-model-define` demonstrates how to create a model class.
31+
- :ref:`laravel-authenticatable-model` shows how to set MongoDB as the
32+
authentication user provider.
33+
- :ref:`laravel-model-customize` explains several model class customizations.
34+
- :ref:`laravel-model-pruning` shows how to periodically remove models that
35+
you no longer need.
36+
37+
.. _laravel-model-define:
38+
39+
Define an Eloquent Model Class
40+
------------------------------
41+
42+
Eloquent models are classes that represent your data. They include methods
43+
that perform database operations such as inserts, updates, and deletes.
44+
45+
To declare a {+odm-short+} model, create a class in the ``app/Models``
46+
directory of your Laravel application that extends
47+
``MongoDB\Laravel\Eloquent\Model`` as shown in the following code example:
48+
49+
.. literalinclude:: /includes/eloquent-models/Planet.php
50+
:language: php
51+
:emphasize-lines: 3,5,7
52+
:dedent:
53+
54+
By default, the model uses the MongoDB database name set in your Laravel
55+
application's ``config/database.php`` setting and the snake case plural
56+
form of your model class name for the collection.
57+
58+
This model is stored in the ``planets`` MongoDB collection.
59+
60+
.. tip::
61+
62+
Alternatively, use the ``artisan`` console to generate the model class and
63+
change the ``Illuminate\Database\Eloquent\Model`` import to ``MongoDB\Laravel\Eloquent\Model``.
64+
To learn more about the ``artisan`` console, see `Artisan Console <https://laravel.com/docs/{+laravel-docs-version+}/artisan>`__
65+
in the Laravel docs.
66+
67+
To learn how to specify the database name that your Laravel application uses,
68+
:ref:`laravel-quick-start-connect-to-mongodb`.
69+
70+
71+
.. _laravel-authenticatable-model:
72+
73+
Extend the Authenticatable Model
74+
--------------------------------
75+
76+
To configure MongoDB as the Laravel user provider, you can extend the
77+
{+odm-short+} ``MongoDB\Laravel\Auth\User`` class. The following code example
78+
shows how to extend this class:
79+
80+
.. literalinclude:: /includes/eloquent-models/AuthenticatableUser.php
81+
:language: php
82+
:emphasize-lines: 3,5,7
83+
:dedent:
84+
85+
To learn more about customizing a Laravel authentication user provider,
86+
see `Adding Custom User Providers <https://laravel.com/docs/{+laravel-docs-version+}/authentication#adding-custom-user-providers>`__
87+
in the Laravel docs.
88+
89+
.. _laravel-model-customize:
90+
91+
Customize an Eloquent Model Class
92+
---------------------------------
93+
94+
This section shows how to perform the following Eloquent model behavior
95+
customizations:
96+
97+
- :ref:`laravel-model-customize-collection-name`
98+
- :ref:`laravel-model-customize-primary-key`
99+
- :ref:`laravel-model-soft-delete`
100+
- :ref:`laravel-model-cast-data-types`
101+
- :ref:`laravel-model-mass-assignment`
102+
103+
.. _laravel-model-customize-collection-name:
104+
105+
Change the Model Collection Name
106+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
107+
108+
By default, the model uses the snake case plural form of your model
109+
class name. To change the name of the collection the model uses to retrieve
110+
and save data in MongoDB, override the ``$collection`` property of the model
111+
class.
112+
113+
.. note::
114+
115+
We recommend using the default collection naming behavior to keep
116+
the associations between models and collections straightforward.
117+
118+
The following example specifies the custom MongoDB collection name,
119+
``celestial_body``, for the ``Planet`` class:
120+
121+
.. literalinclude:: /includes/eloquent-models/PlanetCollection.php
122+
:language: php
123+
:emphasize-lines: 9
124+
:dedent:
125+
126+
Without overriding the ``$collection`` property, this model maps to the
127+
``planets`` collection. With the overridden property, the example class stores
128+
the model in the ``celestial_body`` collection.
129+
130+
.. _laravel-model-customize-primary-key:
131+
132+
Change the Primary Key Field
133+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
134+
135+
To customize the model's primary key field that uniquely identifies a MongoDB
136+
document, override the ``$primaryKey`` property of the model class.
137+
138+
By default, the model uses the PHP MongoDB driver to generate unique ObjectIDs
139+
for each document your Laravel application inserts.
140+
141+
The following example specifies the ``name`` field as the primary key for
142+
the ``Planet`` class:
143+
144+
.. literalinclude:: /includes/eloquent-models/PlanetPrimaryKey.php
145+
:language: php
146+
:emphasize-lines: 9
147+
:dedent:
148+
149+
To learn more about primary key behavior and customization options, see
150+
`Eloquent Primary Keys <https://laravel.com/docs/{+laravel-docs-version+}/eloquent#primary-keys>`__
151+
in the Laravel docs.
152+
153+
To learn more about the ``_id`` field, ObjectIDs, and the MongoDB document
154+
structure, see :manual:`Documents </core/document>` in the MongoDB server docs.
155+
156+
.. _laravel-model-soft-delete:
157+
158+
Enable Soft Deletes
159+
~~~~~~~~~~~~~~~~~~~
160+
161+
Eloquent includes a soft delete feature that changes the behavior of the
162+
``delete()`` method on a model. When soft delete is enabled on a model, the
163+
``delete()`` method marks a document as deleted instead of removing it from the
164+
database. It sets a timestamp on the ``deleted_at`` field to exclude it from
165+
retrieve operations automatically.
166+
167+
To enable soft deletes on a class, add the ``MongoDB\Laravel\Eloquent\SoftDeletes``
168+
trait as shown in the following code example:
169+
170+
.. literalinclude:: /includes/eloquent-models/PlanetSoftDelete.php
171+
:language: php
172+
:emphasize-lines: 6,10
173+
:dedent:
174+
175+
To learn about methods you can perform on models with soft deletes enabled, see
176+
`Eloquent Soft Deleting <https://laravel.com/docs/{+laravel-docs-version+}/eloquent#soft-deleting>`__
177+
in the Laravel docs.
178+
179+
.. _laravel-model-cast-data-types:
180+
181+
Cast Data Types
182+
---------------
183+
184+
Eloquent lets you convert model attribute data types before storing or
185+
retrieving data by using a casting helper. This helper is a convenient
186+
alternative to defining equivalent accessor and mutator methods on your model.
187+
188+
In the following example, the casting helper converts the ``discovery_dt``
189+
model attribute, stored in MongoDB as a `MongoDB\\BSON\\UTCDateTime <https://www.php.net/manual/en/class.mongodb-bson-utcdatetime.php>`__
190+
type, to the Laravel ``datetime`` type.
191+
192+
.. literalinclude:: /includes/eloquent-models/PlanetDate.php
193+
:language: php
194+
:emphasize-lines: 9-11
195+
:dedent:
196+
197+
This conversion lets you use the PHP `DateTime <https://www.php.net/manual/en/class.datetime.php>`__
198+
or the `Carbon class <https://carbon.nesbot.com/docs/>`__ to work with dates
199+
in this field. The following example shows a Laravel query that uses the
200+
casting helper on the model to query for planets with a ``discovery_dt`` of
201+
less than three years ago:
202+
203+
.. code-block:: php
204+
205+
Planet::where( 'discovery_dt', '>', new DateTime('-3 years'))->get();
206+
207+
To learn more about MongoDB's data types, see :manual:`BSON Types </reference/bson-types/>`
208+
in the MongoDB server docs.
209+
210+
To learn more about the Laravel casting helper and supported types, see `Attribute Casting <https://laravel.com/docs/{+laravel-docs-version+}/eloquent-mutators#attribute-casting>`__
211+
in the Laravel docs.
212+
213+
.. _laravel-model-mass-assignment:
214+
215+
Customize Mass Assignment
216+
~~~~~~~~~~~~~~~~~~~~~~~~~
217+
218+
Eloquent lets you create several models and their attribute data by passing
219+
an array of data to the ``create()`` model method. This process of inserting
220+
multiple models is called mass assignment.
221+
222+
Mass assignment can be an efficient way to create multiple models. However, it
223+
can expose an exploitable security vulnerability. The data in the fields
224+
might contain updates that lead to unauthorized permissions or access.
225+
226+
Eloquent provides the following traits to protect your data from mass
227+
assignment vulnerabilities:
228+
229+
- ``$fillable`` contains the fields that are writeable in a mass assignment
230+
- ``$guarded`` contains the fields that are ignored in a mass assignment
231+
232+
.. important::
233+
234+
We recommend using ``$fillable`` instead of ``$guarded`` to protect against
235+
vulnerabilities. To learn more about this recommendation, see the
236+
`Security Release: Laravel 6.18.35, 7.24.0 <https://blog.laravel.com/security-release-laravel-61835-7240>`__
237+
article on the Laravel site.
238+
239+
In the following example, the model allows mass assignment of the fields
240+
by using the ``$fillable`` attribute:
241+
242+
.. literalinclude:: /includes/eloquent-models/PlanetMassAssignment.php
243+
:language: php
244+
:emphasize-lines: 9-14
245+
:dedent:
246+
247+
The following code example shows mass assignment of the ``Planet`` model:
248+
249+
.. code-block:: php
250+
251+
$planets = [
252+
[ 'name' => 'Earth', gravity => 9.8, day_length => '24 hours' ],
253+
[ 'name' => 'Mars', gravity => 3.7, day_length => '25 hours' ],
254+
];
255+
256+
Planet::create($planets);
257+
258+
The models saved to the database contain only the ``name`` and ``gravity``
259+
fields since ``day_length`` is omitted from the ``$fillable`` attribute.
260+
261+
To learn how to change the behavior when attempting to fill a field omitted
262+
from the ``$fillable`` array, see `Mass Assignment Exceptions <https://laravel.com/docs/{+laravel-docs-version+}/eloquent#mass-assignment-exceptions>`__
263+
in the Laravel docs.
264+
265+
.. _laravel-model-pruning:
266+
267+
Specify Pruning Behavior
268+
------------------------
269+
270+
Eloquent lets you specify criteria to periodically delete model data that you
271+
no longer need. When you schedule or run the ``model:prune`` command,
272+
Laravel calls the ``prunable()`` method on all models that import the
273+
``Prunable`` and ``MassPrunable`` traits to match the models for deletion.
274+
275+
To use this feature with models that use MongoDB as a database, add the
276+
appropriate import to your model:
277+
278+
- ``MongoDB\Laravel\Eloquent\Prunable`` optionally performs a cleanup
279+
step before deleting a model that matches the criteria
280+
- ``MongoDB\Laravel\Eloquent\MassPrunable`` deletes models that match the
281+
criteria without fetching the model data
282+
283+
.. note::
284+
285+
When enabling soft deletes on a mass prunable model, you must import the
286+
following {+odm-short+} packages:
287+
288+
- ``MongoDB\Laravel\Eloquent\SoftDeletes``
289+
- ``MongoDB\Laravel\Eloquent\MassPrunable``
290+
291+
292+
To learn more about the pruning feature, see `Pruning Models <https://laravel.com/docs/{+laravel-docs-version+}/eloquent#pruning-models>`__
293+
in the Laravel docs.
294+
295+
Prunable Example
296+
~~~~~~~~~~~~~~~~
297+
298+
The following prunable class includes a ``prunable()`` method that matches
299+
models that the prune action deletes and a ``pruning()`` method that runs
300+
before deleting a matching model:
301+
302+
.. literalinclude:: /includes/eloquent-models/PlanetPrune.php
303+
:language: php
304+
:emphasize-lines: 6,10,12,18
305+
:dedent:
306+
307+
Mass Prunable Example
308+
~~~~~~~~~~~~~~~~~~~~~
309+
310+
The following mass prunable class includes a ``prunable()`` method that matches
311+
models that the prune action deletes:
312+
313+
.. literalinclude:: /includes/eloquent-models/PlanetMassPrune.php
314+
:language: php
315+
:emphasize-lines: 5,10,12
316+
:dedent:
317+

0 commit comments

Comments
 (0)