From 61f150d5ee38e30a551a0c810737e10ce804c770 Mon Sep 17 00:00:00 2001 From: Chris Cho Date: Fri, 9 Feb 2024 17:00:45 -0500 Subject: [PATCH 01/23] DOCSP-35964: Eloquent Models section (WIP) --- docs/eloquent-models.txt | 511 +------------------- docs/eloquent-models/extend-base-model.txt | 522 +++++++++++++++++++++ 2 files changed, 526 insertions(+), 507 deletions(-) create mode 100644 docs/eloquent-models/extend-base-model.txt diff --git a/docs/eloquent-models.txt b/docs/eloquent-models.txt index d10822c37..5408d1c95 100644 --- a/docs/eloquent-models.txt +++ b/docs/eloquent-models.txt @@ -11,512 +11,9 @@ Eloquent Models .. meta:: :keywords: php framework, odm, code example -This package includes a MongoDB enabled Eloquent class that you can use to -define models for corresponding collections. +This section contains information on how you can use the Laravel Eleoquent +models with the {+odm-long+}. -Extending the base model -~~~~~~~~~~~~~~~~~~~~~~~~ +.. toctree:: -To get started, create a new model class in your ``app\Models\`` directory. - -.. code-block:: php - - namespace App\Models; - - use MongoDB\Laravel\Eloquent\Model; - - class Book extends Model - { - // - } - -Just like a regular model, the MongoDB model class will know which collection -to use based on the model name. For ``Book``, the collection ``books`` will -be used. - -To change the collection, pass the ``$collection`` property: - -.. code-block:: php - - use MongoDB\Laravel\Eloquent\Model; - - class Book extends Model - { - protected $collection = 'my_books_collection'; - } - -.. note:: - - MongoDB documents are automatically stored with a unique ID that is stored - in the ``_id`` property. If you wish to use your own ID, substitute the - ``$primaryKey`` property and set it to your own primary key attribute name. - -.. code-block:: php - - use MongoDB\Laravel\Eloquent\Model; - - class Book extends Model - { - protected $primaryKey = 'id'; - } - - // MongoDB will also create _id, but the 'id' property will be used for primary key actions like find(). - Book::create(['id' => 1, 'title' => 'The Fault in Our Stars']); - -Likewise, you may define a ``connection`` property to override the name of the -database connection to reference the model. - -.. code-block:: php - - use MongoDB\Laravel\Eloquent\Model; - - class Book extends Model - { - protected $connection = 'mongodb'; - } - -Soft Deletes -~~~~~~~~~~~~ - -When soft deleting a model, it is not actually removed from your database. -Instead, a ``deleted_at`` timestamp is set on the record. - -To enable soft delete for a model, apply the ``MongoDB\Laravel\Eloquent\SoftDeletes`` -Trait to the model: - -.. code-block:: php - - use MongoDB\Laravel\Eloquent\SoftDeletes; - - class User extends Model - { - use SoftDeletes; - } - -For more information check `Laravel Docs about Soft Deleting `__. - -Prunable -~~~~~~~~ - -``Prunable`` and ``MassPrunable`` traits are Laravel features to automatically -remove models from your database. You can use ``Illuminate\Database\Eloquent\Prunable`` -trait to remove models one by one. If you want to remove models in bulk, you -must use the ``MongoDB\Laravel\Eloquent\MassPrunable`` trait instead: it -will be more performant but can break links with other documents as it does -not load the models. - -.. code-block:: php - - use MongoDB\Laravel\Eloquent\Model; - use MongoDB\Laravel\Eloquent\MassPrunable; - - class Book extends Model - { - use MassPrunable; - } - -For more information check `Laravel Docs about Pruning Models `__. - -Dates -~~~~~ - -Eloquent allows you to work with Carbon or DateTime objects instead of MongoDate objects. Internally, these dates will be converted to MongoDate objects when saved to the database. - -.. code-block:: php - - use MongoDB\Laravel\Eloquent\Model; - - class User extends Model - { - protected $casts = ['birthday' => 'datetime']; - } - -This allows you to execute queries like this: - -.. code-block:: php - - $users = User::where( - 'birthday', '>', - new DateTime('-18 years') - )->get(); - -Extending the Authenticatable base model -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -This package includes a MongoDB Authenticatable Eloquent class ``MongoDB\Laravel\Auth\User`` -that you can use to replace the default Authenticatable class ``Illuminate\Foundation\Auth\User`` -for your ``User`` model. - -.. code-block:: php - - use MongoDB\Laravel\Auth\User as Authenticatable; - - class User extends Authenticatable - { - - } - -Guarding attributes -~~~~~~~~~~~~~~~~~~~ - -When choosing between guarding attributes or marking some as fillable, Taylor -Otwell prefers the fillable route. This is in light of -`recent security issues described here `__. - -Keep in mind guarding still works, but you may experience unexpected behavior. - -Schema ------- - -The database driver also has (limited) schema builder support. You can -conveniently manipulate collections and set indexes. - -Basic Usage -~~~~~~~~~~~ - -.. code-block:: php - - Schema::create('users', function ($collection) { - $collection->index('name'); - $collection->unique('email'); - }); - -You can also pass all the parameters specified :manual:`in the MongoDB docs ` -to the ``$options`` parameter: - -.. code-block:: php - - Schema::create('users', function ($collection) { - $collection->index( - 'username', - null, - null, - [ - 'sparse' => true, - 'unique' => true, - 'background' => true, - ] - ); - }); - -Inherited operations: - - -* create and drop -* collection -* hasCollection -* index and dropIndex (compound indexes supported as well) -* unique - -MongoDB specific operations: - - -* background -* sparse -* expire -* geospatial - -All other (unsupported) operations are implemented as dummy pass-through -methods because MongoDB does not use a predefined schema. - -Read more about the schema builder on `Laravel Docs `__ - -Geospatial indexes -~~~~~~~~~~~~~~~~~~ - -Geospatial indexes can improve query performance of location-based documents. - -They come in two forms: ``2d`` and ``2dsphere``. Use the schema builder to add -these to a collection. - -.. code-block:: php - - Schema::create('bars', function ($collection) { - $collection->geospatial('location', '2d'); - }); - -To add a ``2dsphere`` index: - -.. code-block:: php - - Schema::create('bars', function ($collection) { - $collection->geospatial('location', '2dsphere'); - }); - -Relationships -------------- - -Basic Usage -~~~~~~~~~~~ - -The only available relationships are: - - -* hasOne -* hasMany -* belongsTo -* belongsToMany - -The MongoDB-specific relationships are: - - -* embedsOne -* embedsMany - -Here is a small example: - -.. code-block:: php - - use MongoDB\Laravel\Eloquent\Model; - - class User extends Model - { - public function items() - { - return $this->hasMany(Item::class); - } - } - -The inverse relation of ``hasMany`` is ``belongsTo``: - -.. code-block:: php - - use MongoDB\Laravel\Eloquent\Model; - - class Item extends Model - { - public function user() - { - return $this->belongsTo(User::class); - } - } - -belongsToMany and pivots -~~~~~~~~~~~~~~~~~~~~~~~~ - -The belongsToMany relation will not use a pivot "table" but will push id's to -a **related_ids** attribute instead. This makes the second parameter for the -belongsToMany method useless. - -If you want to define custom keys for your relation, set it to ``null``: - -.. code-block:: php - - use MongoDB\Laravel\Eloquent\Model; - - class User extends Model - { - public function groups() - { - return $this->belongsToMany( - Group::class, null, 'user_ids', 'group_ids' - ); - } - } - -EmbedsMany Relationship -~~~~~~~~~~~~~~~~~~~~~~~ - -If you want to embed models, rather than referencing them, you can use the -``embedsMany`` relation. This relation is similar to the ``hasMany`` relation -but embeds the models inside the parent object. - -**REMEMBER**\ : These relations return Eloquent collections, they don't return -query builder objects! - -.. code-block:: php - - use MongoDB\Laravel\Eloquent\Model; - - class User extends Model - { - public function books() - { - return $this->embedsMany(Book::class); - } - } - -You can access the embedded models through the dynamic property: - -.. code-block:: php - - $user = User::first(); - - foreach ($user->books as $book) { - // - } - -The inverse relation is auto *magically* available. You can omit the reverse -relation definition. - -.. code-block:: php - - $book = Book::first(); - - $user = $book->user; - -Inserting and updating embedded models works similar to the ``hasMany`` relation: - -.. code-block:: php - - $book = $user->books()->save( - new Book(['title' => 'A Game of Thrones']) - ); - - // or - $book = - $user->books() - ->create(['title' => 'A Game of Thrones']); - -You can update embedded models using their ``save`` method (available since -release 2.0.0): - -.. code-block:: php - - $book = $user->books()->first(); - - $book->title = 'A Game of Thrones'; - $book->save(); - -You can remove an embedded model by using the ``destroy`` method on the -relation, or the ``delete`` method on the model (available since release 2.0.0): - -.. code-block:: php - - $book->delete(); - - // Similar operation - $user->books()->destroy($book); - -If you want to add or remove an embedded model, without touching the database, -you can use the ``associate`` and ``dissociate`` methods. - -To eventually write the changes to the database, save the parent object: - -.. code-block:: php - - $user->books()->associate($book); - $user->save(); - -Like other relations, embedsMany assumes the local key of the relationship -based on the model name. You can override the default local key by passing a -second argument to the embedsMany method: - -.. code-block:: php - - use MongoDB\Laravel\Eloquent\Model; - - class User extends Model - { - public function books() - { - return $this->embedsMany(Book::class, 'local_key'); - } - } - -Embedded relations will return a Collection of embedded items instead of a -query builder. Check out the available operations here: -`https://laravel.com/docs/master/collections `__ - -EmbedsOne Relationship -~~~~~~~~~~~~~~~~~~~~~~ - -The embedsOne relation is similar to the embedsMany relation, but only embeds a single model. - -.. code-block:: php - - use MongoDB\Laravel\Eloquent\Model; - - class Book extends Model - { - public function author() - { - return $this->embedsOne(Author::class); - } - } - -You can access the embedded models through the dynamic property: - -.. code-block:: php - - $book = Book::first(); - $author = $book->author; - -Inserting and updating embedded models works similar to the ``hasOne`` relation: - -.. code-block:: php - - $author = $book->author()->save( - new Author(['name' => 'John Doe']) - ); - - // Similar - $author = - $book->author() - ->create(['name' => 'John Doe']); - -You can update the embedded model using the ``save`` method (available since -release 2.0.0): - -.. code-block:: php - - $author = $book->author; - - $author->name = 'Jane Doe'; - $author->save(); - -You can replace the embedded model with a new model like this: - -.. code-block:: php - - $newAuthor = new Author(['name' => 'Jane Doe']); - - $book->author()->save($newAuthor); - -Cross-Database Relationships ----------------------------- - -If you're using a hybrid MongoDB and SQL setup, you can define relationships -across them. - -The model will automatically return a MongoDB-related or SQL-related relation -based on the type of the related model. - -If you want this functionality to work both ways, your SQL-models will need -to use the ``MongoDB\Laravel\Eloquent\HybridRelations`` trait. - -**This functionality only works for ``hasOne``, ``hasMany`` and ``belongsTo``.** - -The SQL model must use the ``HybridRelations`` trait: - -.. code-block:: php - - use MongoDB\Laravel\Eloquent\HybridRelations; - - class User extends Model - { - use HybridRelations; - - protected $connection = 'mysql'; - - public function messages() - { - return $this->hasMany(Message::class); - } - } - -Within your MongoDB model, you must define the following relationship: - -.. code-block:: php - - use MongoDB\Laravel\Eloquent\Model; - - class Message extends Model - { - protected $connection = 'mongodb'; - - public function user() - { - return $this->belongsTo(User::class); - } - } + /eloquent-models/extend-base-model/ diff --git a/docs/eloquent-models/extend-base-model.txt b/docs/eloquent-models/extend-base-model.txt new file mode 100644 index 000000000..d10822c37 --- /dev/null +++ b/docs/eloquent-models/extend-base-model.txt @@ -0,0 +1,522 @@ +.. _laravel-eloquent-models: + +=============== +Eloquent Models +=============== + +.. facet:: + :name: genre + :values: tutorial + +.. meta:: + :keywords: php framework, odm, code example + +This package includes a MongoDB enabled Eloquent class that you can use to +define models for corresponding collections. + +Extending the base model +~~~~~~~~~~~~~~~~~~~~~~~~ + +To get started, create a new model class in your ``app\Models\`` directory. + +.. code-block:: php + + namespace App\Models; + + use MongoDB\Laravel\Eloquent\Model; + + class Book extends Model + { + // + } + +Just like a regular model, the MongoDB model class will know which collection +to use based on the model name. For ``Book``, the collection ``books`` will +be used. + +To change the collection, pass the ``$collection`` property: + +.. code-block:: php + + use MongoDB\Laravel\Eloquent\Model; + + class Book extends Model + { + protected $collection = 'my_books_collection'; + } + +.. note:: + + MongoDB documents are automatically stored with a unique ID that is stored + in the ``_id`` property. If you wish to use your own ID, substitute the + ``$primaryKey`` property and set it to your own primary key attribute name. + +.. code-block:: php + + use MongoDB\Laravel\Eloquent\Model; + + class Book extends Model + { + protected $primaryKey = 'id'; + } + + // MongoDB will also create _id, but the 'id' property will be used for primary key actions like find(). + Book::create(['id' => 1, 'title' => 'The Fault in Our Stars']); + +Likewise, you may define a ``connection`` property to override the name of the +database connection to reference the model. + +.. code-block:: php + + use MongoDB\Laravel\Eloquent\Model; + + class Book extends Model + { + protected $connection = 'mongodb'; + } + +Soft Deletes +~~~~~~~~~~~~ + +When soft deleting a model, it is not actually removed from your database. +Instead, a ``deleted_at`` timestamp is set on the record. + +To enable soft delete for a model, apply the ``MongoDB\Laravel\Eloquent\SoftDeletes`` +Trait to the model: + +.. code-block:: php + + use MongoDB\Laravel\Eloquent\SoftDeletes; + + class User extends Model + { + use SoftDeletes; + } + +For more information check `Laravel Docs about Soft Deleting `__. + +Prunable +~~~~~~~~ + +``Prunable`` and ``MassPrunable`` traits are Laravel features to automatically +remove models from your database. You can use ``Illuminate\Database\Eloquent\Prunable`` +trait to remove models one by one. If you want to remove models in bulk, you +must use the ``MongoDB\Laravel\Eloquent\MassPrunable`` trait instead: it +will be more performant but can break links with other documents as it does +not load the models. + +.. code-block:: php + + use MongoDB\Laravel\Eloquent\Model; + use MongoDB\Laravel\Eloquent\MassPrunable; + + class Book extends Model + { + use MassPrunable; + } + +For more information check `Laravel Docs about Pruning Models `__. + +Dates +~~~~~ + +Eloquent allows you to work with Carbon or DateTime objects instead of MongoDate objects. Internally, these dates will be converted to MongoDate objects when saved to the database. + +.. code-block:: php + + use MongoDB\Laravel\Eloquent\Model; + + class User extends Model + { + protected $casts = ['birthday' => 'datetime']; + } + +This allows you to execute queries like this: + +.. code-block:: php + + $users = User::where( + 'birthday', '>', + new DateTime('-18 years') + )->get(); + +Extending the Authenticatable base model +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +This package includes a MongoDB Authenticatable Eloquent class ``MongoDB\Laravel\Auth\User`` +that you can use to replace the default Authenticatable class ``Illuminate\Foundation\Auth\User`` +for your ``User`` model. + +.. code-block:: php + + use MongoDB\Laravel\Auth\User as Authenticatable; + + class User extends Authenticatable + { + + } + +Guarding attributes +~~~~~~~~~~~~~~~~~~~ + +When choosing between guarding attributes or marking some as fillable, Taylor +Otwell prefers the fillable route. This is in light of +`recent security issues described here `__. + +Keep in mind guarding still works, but you may experience unexpected behavior. + +Schema +------ + +The database driver also has (limited) schema builder support. You can +conveniently manipulate collections and set indexes. + +Basic Usage +~~~~~~~~~~~ + +.. code-block:: php + + Schema::create('users', function ($collection) { + $collection->index('name'); + $collection->unique('email'); + }); + +You can also pass all the parameters specified :manual:`in the MongoDB docs ` +to the ``$options`` parameter: + +.. code-block:: php + + Schema::create('users', function ($collection) { + $collection->index( + 'username', + null, + null, + [ + 'sparse' => true, + 'unique' => true, + 'background' => true, + ] + ); + }); + +Inherited operations: + + +* create and drop +* collection +* hasCollection +* index and dropIndex (compound indexes supported as well) +* unique + +MongoDB specific operations: + + +* background +* sparse +* expire +* geospatial + +All other (unsupported) operations are implemented as dummy pass-through +methods because MongoDB does not use a predefined schema. + +Read more about the schema builder on `Laravel Docs `__ + +Geospatial indexes +~~~~~~~~~~~~~~~~~~ + +Geospatial indexes can improve query performance of location-based documents. + +They come in two forms: ``2d`` and ``2dsphere``. Use the schema builder to add +these to a collection. + +.. code-block:: php + + Schema::create('bars', function ($collection) { + $collection->geospatial('location', '2d'); + }); + +To add a ``2dsphere`` index: + +.. code-block:: php + + Schema::create('bars', function ($collection) { + $collection->geospatial('location', '2dsphere'); + }); + +Relationships +------------- + +Basic Usage +~~~~~~~~~~~ + +The only available relationships are: + + +* hasOne +* hasMany +* belongsTo +* belongsToMany + +The MongoDB-specific relationships are: + + +* embedsOne +* embedsMany + +Here is a small example: + +.. code-block:: php + + use MongoDB\Laravel\Eloquent\Model; + + class User extends Model + { + public function items() + { + return $this->hasMany(Item::class); + } + } + +The inverse relation of ``hasMany`` is ``belongsTo``: + +.. code-block:: php + + use MongoDB\Laravel\Eloquent\Model; + + class Item extends Model + { + public function user() + { + return $this->belongsTo(User::class); + } + } + +belongsToMany and pivots +~~~~~~~~~~~~~~~~~~~~~~~~ + +The belongsToMany relation will not use a pivot "table" but will push id's to +a **related_ids** attribute instead. This makes the second parameter for the +belongsToMany method useless. + +If you want to define custom keys for your relation, set it to ``null``: + +.. code-block:: php + + use MongoDB\Laravel\Eloquent\Model; + + class User extends Model + { + public function groups() + { + return $this->belongsToMany( + Group::class, null, 'user_ids', 'group_ids' + ); + } + } + +EmbedsMany Relationship +~~~~~~~~~~~~~~~~~~~~~~~ + +If you want to embed models, rather than referencing them, you can use the +``embedsMany`` relation. This relation is similar to the ``hasMany`` relation +but embeds the models inside the parent object. + +**REMEMBER**\ : These relations return Eloquent collections, they don't return +query builder objects! + +.. code-block:: php + + use MongoDB\Laravel\Eloquent\Model; + + class User extends Model + { + public function books() + { + return $this->embedsMany(Book::class); + } + } + +You can access the embedded models through the dynamic property: + +.. code-block:: php + + $user = User::first(); + + foreach ($user->books as $book) { + // + } + +The inverse relation is auto *magically* available. You can omit the reverse +relation definition. + +.. code-block:: php + + $book = Book::first(); + + $user = $book->user; + +Inserting and updating embedded models works similar to the ``hasMany`` relation: + +.. code-block:: php + + $book = $user->books()->save( + new Book(['title' => 'A Game of Thrones']) + ); + + // or + $book = + $user->books() + ->create(['title' => 'A Game of Thrones']); + +You can update embedded models using their ``save`` method (available since +release 2.0.0): + +.. code-block:: php + + $book = $user->books()->first(); + + $book->title = 'A Game of Thrones'; + $book->save(); + +You can remove an embedded model by using the ``destroy`` method on the +relation, or the ``delete`` method on the model (available since release 2.0.0): + +.. code-block:: php + + $book->delete(); + + // Similar operation + $user->books()->destroy($book); + +If you want to add or remove an embedded model, without touching the database, +you can use the ``associate`` and ``dissociate`` methods. + +To eventually write the changes to the database, save the parent object: + +.. code-block:: php + + $user->books()->associate($book); + $user->save(); + +Like other relations, embedsMany assumes the local key of the relationship +based on the model name. You can override the default local key by passing a +second argument to the embedsMany method: + +.. code-block:: php + + use MongoDB\Laravel\Eloquent\Model; + + class User extends Model + { + public function books() + { + return $this->embedsMany(Book::class, 'local_key'); + } + } + +Embedded relations will return a Collection of embedded items instead of a +query builder. Check out the available operations here: +`https://laravel.com/docs/master/collections `__ + +EmbedsOne Relationship +~~~~~~~~~~~~~~~~~~~~~~ + +The embedsOne relation is similar to the embedsMany relation, but only embeds a single model. + +.. code-block:: php + + use MongoDB\Laravel\Eloquent\Model; + + class Book extends Model + { + public function author() + { + return $this->embedsOne(Author::class); + } + } + +You can access the embedded models through the dynamic property: + +.. code-block:: php + + $book = Book::first(); + $author = $book->author; + +Inserting and updating embedded models works similar to the ``hasOne`` relation: + +.. code-block:: php + + $author = $book->author()->save( + new Author(['name' => 'John Doe']) + ); + + // Similar + $author = + $book->author() + ->create(['name' => 'John Doe']); + +You can update the embedded model using the ``save`` method (available since +release 2.0.0): + +.. code-block:: php + + $author = $book->author; + + $author->name = 'Jane Doe'; + $author->save(); + +You can replace the embedded model with a new model like this: + +.. code-block:: php + + $newAuthor = new Author(['name' => 'Jane Doe']); + + $book->author()->save($newAuthor); + +Cross-Database Relationships +---------------------------- + +If you're using a hybrid MongoDB and SQL setup, you can define relationships +across them. + +The model will automatically return a MongoDB-related or SQL-related relation +based on the type of the related model. + +If you want this functionality to work both ways, your SQL-models will need +to use the ``MongoDB\Laravel\Eloquent\HybridRelations`` trait. + +**This functionality only works for ``hasOne``, ``hasMany`` and ``belongsTo``.** + +The SQL model must use the ``HybridRelations`` trait: + +.. code-block:: php + + use MongoDB\Laravel\Eloquent\HybridRelations; + + class User extends Model + { + use HybridRelations; + + protected $connection = 'mysql'; + + public function messages() + { + return $this->hasMany(Message::class); + } + } + +Within your MongoDB model, you must define the following relationship: + +.. code-block:: php + + use MongoDB\Laravel\Eloquent\Model; + + class Message extends Model + { + protected $connection = 'mongodb'; + + public function user() + { + return $this->belongsTo(User::class); + } + } From d765e7b6723a3a438c8f70f36f793c0138a91579 Mon Sep 17 00:00:00 2001 From: Chris Cho Date: Fri, 9 Feb 2024 17:26:00 -0500 Subject: [PATCH 02/23] split files --- docs/eloquent-models.txt | 4 + docs/eloquent-models/extend-base-model.txt | 8 +- docs/eloquent-models/geo-index.txt | 32 +++ docs/eloquent-models/relationships.txt | 290 +++++++++++++++++++++ docs/eloquent-models/schema-builder.txt | 58 +++++ 5 files changed, 388 insertions(+), 4 deletions(-) create mode 100644 docs/eloquent-models/geo-index.txt create mode 100644 docs/eloquent-models/relationships.txt create mode 100644 docs/eloquent-models/schema-builder.txt diff --git a/docs/eloquent-models.txt b/docs/eloquent-models.txt index 5408d1c95..b41cb0b98 100644 --- a/docs/eloquent-models.txt +++ b/docs/eloquent-models.txt @@ -17,3 +17,7 @@ models with the {+odm-long+}. .. toctree:: /eloquent-models/extend-base-model/ + /eloquent-models/schema-builder/ + /eloquent-models/relationships/ + /eloquent-models/geo-index/ + diff --git a/docs/eloquent-models/extend-base-model.txt b/docs/eloquent-models/extend-base-model.txt index d10822c37..ba17f1d13 100644 --- a/docs/eloquent-models/extend-base-model.txt +++ b/docs/eloquent-models/extend-base-model.txt @@ -1,8 +1,8 @@ -.. _laravel-eloquent-models: +.. _laravel-eloquent-model-class: -=============== -Eloquent Models -=============== +===================== +Eloquent Model Class +==================== .. facet:: :name: genre diff --git a/docs/eloquent-models/geo-index.txt b/docs/eloquent-models/geo-index.txt new file mode 100644 index 000000000..fdca6b92a --- /dev/null +++ b/docs/eloquent-models/geo-index.txt @@ -0,0 +1,32 @@ +.. _laravel-eloquent-model-geospatial-index: + +================== +Geospatial Indexes +================== + +.. facet:: + :name: genre + :values: tutorial + +.. meta:: + :keywords: php framework, odm, code example + +Geospatial indexes can improve query performance of location-based documents. + +They come in two forms: ``2d`` and ``2dsphere``. Use the schema builder to add +these to a collection. + +.. code-block:: php + + Schema::create('bars', function ($collection) { + $collection->geospatial('location', '2d'); + }); + +To add a ``2dsphere`` index: + +.. code-block:: php + + Schema::create('bars', function ($collection) { + $collection->geospatial('location', '2dsphere'); + }); + diff --git a/docs/eloquent-models/relationships.txt b/docs/eloquent-models/relationships.txt new file mode 100644 index 000000000..69a56d03e --- /dev/null +++ b/docs/eloquent-models/relationships.txt @@ -0,0 +1,290 @@ +.. _laravel-eloquent-model-relationships: + +============================ +Eloquent Model Relationships +============================ + +.. facet:: + :name: genre + :values: tutorial + +.. meta:: + :keywords: php framework, odm, code example + +Relationships +------------- + +Basic Usage +~~~~~~~~~~~ + +The only available relationships are: + + +* hasOne +* hasMany +* belongsTo +* belongsToMany + +The MongoDB-specific relationships are: + + +* embedsOne +* embedsMany + +Here is a small example: + +.. code-block:: php + + use MongoDB\Laravel\Eloquent\Model; + + class User extends Model + { + public function items() + { + return $this->hasMany(Item::class); + } + } + +The inverse relation of ``hasMany`` is ``belongsTo``: + +.. code-block:: php + + use MongoDB\Laravel\Eloquent\Model; + + class Item extends Model + { + public function user() + { + return $this->belongsTo(User::class); + } + } + +belongsToMany and pivots +~~~~~~~~~~~~~~~~~~~~~~~~ + +The belongsToMany relation will not use a pivot "table" but will push id's to +a **related_ids** attribute instead. This makes the second parameter for the +belongsToMany method useless. + +If you want to define custom keys for your relation, set it to ``null``: + +.. code-block:: php + + use MongoDB\Laravel\Eloquent\Model; + + class User extends Model + { + public function groups() + { + return $this->belongsToMany( + Group::class, null, 'user_ids', 'group_ids' + ); + } + } + +EmbedsMany Relationship +~~~~~~~~~~~~~~~~~~~~~~~ + +If you want to embed models, rather than referencing them, you can use the +``embedsMany`` relation. This relation is similar to the ``hasMany`` relation +but embeds the models inside the parent object. + +**REMEMBER**\ : These relations return Eloquent collections, they don't return +query builder objects! + +.. code-block:: php + + use MongoDB\Laravel\Eloquent\Model; + + class User extends Model + { + public function books() + { + return $this->embedsMany(Book::class); + } + } + +You can access the embedded models through the dynamic property: + +.. code-block:: php + + $user = User::first(); + + foreach ($user->books as $book) { + // + } + +The inverse relation is auto *magically* available. You can omit the reverse +relation definition. + +.. code-block:: php + + $book = Book::first(); + + $user = $book->user; + +Inserting and updating embedded models works similar to the ``hasMany`` relation: + +.. code-block:: php + + $book = $user->books()->save( + new Book(['title' => 'A Game of Thrones']) + ); + + // or + $book = + $user->books() + ->create(['title' => 'A Game of Thrones']); + +You can update embedded models using their ``save`` method (available since +release 2.0.0): + +.. code-block:: php + + $book = $user->books()->first(); + + $book->title = 'A Game of Thrones'; + $book->save(); + +You can remove an embedded model by using the ``destroy`` method on the +relation, or the ``delete`` method on the model (available since release 2.0.0): + +.. code-block:: php + + $book->delete(); + + // Similar operation + $user->books()->destroy($book); + +If you want to add or remove an embedded model, without touching the database, +you can use the ``associate`` and ``dissociate`` methods. + +To eventually write the changes to the database, save the parent object: + +.. code-block:: php + + $user->books()->associate($book); + $user->save(); + +Like other relations, embedsMany assumes the local key of the relationship +based on the model name. You can override the default local key by passing a +second argument to the embedsMany method: + +.. code-block:: php + + use MongoDB\Laravel\Eloquent\Model; + + class User extends Model + { + public function books() + { + return $this->embedsMany(Book::class, 'local_key'); + } + } + +Embedded relations will return a Collection of embedded items instead of a +query builder. Check out the available operations here: +`https://laravel.com/docs/master/collections `__ + +EmbedsOne Relationship +~~~~~~~~~~~~~~~~~~~~~~ + +The embedsOne relation is similar to the embedsMany relation, but only embeds a single model. + +.. code-block:: php + + use MongoDB\Laravel\Eloquent\Model; + + class Book extends Model + { + public function author() + { + return $this->embedsOne(Author::class); + } + } + +You can access the embedded models through the dynamic property: + +.. code-block:: php + + $book = Book::first(); + $author = $book->author; + +Inserting and updating embedded models works similar to the ``hasOne`` relation: + +.. code-block:: php + + $author = $book->author()->save( + new Author(['name' => 'John Doe']) + ); + + // Similar + $author = + $book->author() + ->create(['name' => 'John Doe']); + +You can update the embedded model using the ``save`` method (available since +release 2.0.0): + +.. code-block:: php + + $author = $book->author; + + $author->name = 'Jane Doe'; + $author->save(); + +You can replace the embedded model with a new model like this: + +.. code-block:: php + + $newAuthor = new Author(['name' => 'Jane Doe']); + + $book->author()->save($newAuthor); + +Cross-Database Relationships +---------------------------- + +If you're using a hybrid MongoDB and SQL setup, you can define relationships +across them. + +The model will automatically return a MongoDB-related or SQL-related relation +based on the type of the related model. + +If you want this functionality to work both ways, your SQL-models will need +to use the ``MongoDB\Laravel\Eloquent\HybridRelations`` trait. + +**This functionality only works for ``hasOne``, ``hasMany`` and ``belongsTo``.** + +The SQL model must use the ``HybridRelations`` trait: + +.. code-block:: php + + use MongoDB\Laravel\Eloquent\HybridRelations; + + class User extends Model + { + use HybridRelations; + + protected $connection = 'mysql'; + + public function messages() + { + return $this->hasMany(Message::class); + } + } + +Within your MongoDB model, you must define the following relationship: + +.. code-block:: php + + use MongoDB\Laravel\Eloquent\Model; + + class Message extends Model + { + protected $connection = 'mongodb'; + + public function user() + { + return $this->belongsTo(User::class); + } + } diff --git a/docs/eloquent-models/schema-builder.txt b/docs/eloquent-models/schema-builder.txt new file mode 100644 index 000000000..8bfcfeccb --- /dev/null +++ b/docs/eloquent-models/schema-builder.txt @@ -0,0 +1,58 @@ +.. _laravel-eloquent-model-schema-builder: + +============== +Schema Builder +============== + +The database driver also has (limited) schema builder support. You can +conveniently manipulate collections and set indexes. + +Basic Usage +~~~~~~~~~~~ + +.. code-block:: php + + Schema::create('users', function ($collection) { + $collection->index('name'); + $collection->unique('email'); + }); + +You can also pass all the parameters specified :manual:`in the MongoDB docs ` +to the ``$options`` parameter: + +.. code-block:: php + + Schema::create('users', function ($collection) { + $collection->index( + 'username', + null, + null, + [ + 'sparse' => true, + 'unique' => true, + 'background' => true, + ] + ); + }); + +Inherited operations: + + +* create and drop +* collection +* hasCollection +* index and dropIndex (compound indexes supported as well) +* unique + +MongoDB specific operations: + + +* background +* sparse +* expire +* geospatial + +All other (unsupported) operations are implemented as dummy pass-through +methods because MongoDB does not use a predefined schema. + +Read more about the schema builder on `Laravel Docs `__ From e4d05f928e247f42442eaf315d3336e00ad183b6 Mon Sep 17 00:00:00 2001 From: Chris Cho Date: Mon, 12 Feb 2024 14:52:23 -0500 Subject: [PATCH 03/23] outline --- docs/eloquent-models.txt | 19 +- docs/eloquent-models/extend-base-model.txt | 522 --------------------- docs/eloquent-models/geo-index.txt | 32 -- docs/eloquent-models/model-class.txt | 24 + docs/eloquent-models/relationships.txt | 276 +---------- docs/eloquent-models/schema-builder.txt | 56 +-- 6 files changed, 49 insertions(+), 880 deletions(-) delete mode 100644 docs/eloquent-models/extend-base-model.txt delete mode 100644 docs/eloquent-models/geo-index.txt create mode 100644 docs/eloquent-models/model-class.txt diff --git a/docs/eloquent-models.txt b/docs/eloquent-models.txt index b41cb0b98..c2267231f 100644 --- a/docs/eloquent-models.txt +++ b/docs/eloquent-models.txt @@ -6,18 +6,25 @@ Eloquent Models .. facet:: :name: genre - :values: tutorial + :values: reference .. meta:: - :keywords: php framework, odm, code example + :keywords: php framework, odm -This section contains information on how you can use the Laravel Eleoquent -models with the {+odm-long+}. +This landing page will briefly describe Eloquent models and how +Laravel MongoDB extends it. This will be a landing page that identifies where +users can find information on a particular Eloquent model topic. + +Learn how to use Laravel Eloquent models in the {+odm-long+} to work with +MongoDB in the following sections: + +- :ref:`laravel-eloquent-model-class` +- :ref:`laravel-eloquent-model-schema-builder` +- :ref:`laravel-eloquent-model-relationships` .. toctree:: - /eloquent-models/extend-base-model/ + /eloquent-models/model-class/ /eloquent-models/schema-builder/ /eloquent-models/relationships/ - /eloquent-models/geo-index/ diff --git a/docs/eloquent-models/extend-base-model.txt b/docs/eloquent-models/extend-base-model.txt deleted file mode 100644 index ba17f1d13..000000000 --- a/docs/eloquent-models/extend-base-model.txt +++ /dev/null @@ -1,522 +0,0 @@ -.. _laravel-eloquent-model-class: - -===================== -Eloquent Model Class -==================== - -.. facet:: - :name: genre - :values: tutorial - -.. meta:: - :keywords: php framework, odm, code example - -This package includes a MongoDB enabled Eloquent class that you can use to -define models for corresponding collections. - -Extending the base model -~~~~~~~~~~~~~~~~~~~~~~~~ - -To get started, create a new model class in your ``app\Models\`` directory. - -.. code-block:: php - - namespace App\Models; - - use MongoDB\Laravel\Eloquent\Model; - - class Book extends Model - { - // - } - -Just like a regular model, the MongoDB model class will know which collection -to use based on the model name. For ``Book``, the collection ``books`` will -be used. - -To change the collection, pass the ``$collection`` property: - -.. code-block:: php - - use MongoDB\Laravel\Eloquent\Model; - - class Book extends Model - { - protected $collection = 'my_books_collection'; - } - -.. note:: - - MongoDB documents are automatically stored with a unique ID that is stored - in the ``_id`` property. If you wish to use your own ID, substitute the - ``$primaryKey`` property and set it to your own primary key attribute name. - -.. code-block:: php - - use MongoDB\Laravel\Eloquent\Model; - - class Book extends Model - { - protected $primaryKey = 'id'; - } - - // MongoDB will also create _id, but the 'id' property will be used for primary key actions like find(). - Book::create(['id' => 1, 'title' => 'The Fault in Our Stars']); - -Likewise, you may define a ``connection`` property to override the name of the -database connection to reference the model. - -.. code-block:: php - - use MongoDB\Laravel\Eloquent\Model; - - class Book extends Model - { - protected $connection = 'mongodb'; - } - -Soft Deletes -~~~~~~~~~~~~ - -When soft deleting a model, it is not actually removed from your database. -Instead, a ``deleted_at`` timestamp is set on the record. - -To enable soft delete for a model, apply the ``MongoDB\Laravel\Eloquent\SoftDeletes`` -Trait to the model: - -.. code-block:: php - - use MongoDB\Laravel\Eloquent\SoftDeletes; - - class User extends Model - { - use SoftDeletes; - } - -For more information check `Laravel Docs about Soft Deleting `__. - -Prunable -~~~~~~~~ - -``Prunable`` and ``MassPrunable`` traits are Laravel features to automatically -remove models from your database. You can use ``Illuminate\Database\Eloquent\Prunable`` -trait to remove models one by one. If you want to remove models in bulk, you -must use the ``MongoDB\Laravel\Eloquent\MassPrunable`` trait instead: it -will be more performant but can break links with other documents as it does -not load the models. - -.. code-block:: php - - use MongoDB\Laravel\Eloquent\Model; - use MongoDB\Laravel\Eloquent\MassPrunable; - - class Book extends Model - { - use MassPrunable; - } - -For more information check `Laravel Docs about Pruning Models `__. - -Dates -~~~~~ - -Eloquent allows you to work with Carbon or DateTime objects instead of MongoDate objects. Internally, these dates will be converted to MongoDate objects when saved to the database. - -.. code-block:: php - - use MongoDB\Laravel\Eloquent\Model; - - class User extends Model - { - protected $casts = ['birthday' => 'datetime']; - } - -This allows you to execute queries like this: - -.. code-block:: php - - $users = User::where( - 'birthday', '>', - new DateTime('-18 years') - )->get(); - -Extending the Authenticatable base model -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -This package includes a MongoDB Authenticatable Eloquent class ``MongoDB\Laravel\Auth\User`` -that you can use to replace the default Authenticatable class ``Illuminate\Foundation\Auth\User`` -for your ``User`` model. - -.. code-block:: php - - use MongoDB\Laravel\Auth\User as Authenticatable; - - class User extends Authenticatable - { - - } - -Guarding attributes -~~~~~~~~~~~~~~~~~~~ - -When choosing between guarding attributes or marking some as fillable, Taylor -Otwell prefers the fillable route. This is in light of -`recent security issues described here `__. - -Keep in mind guarding still works, but you may experience unexpected behavior. - -Schema ------- - -The database driver also has (limited) schema builder support. You can -conveniently manipulate collections and set indexes. - -Basic Usage -~~~~~~~~~~~ - -.. code-block:: php - - Schema::create('users', function ($collection) { - $collection->index('name'); - $collection->unique('email'); - }); - -You can also pass all the parameters specified :manual:`in the MongoDB docs ` -to the ``$options`` parameter: - -.. code-block:: php - - Schema::create('users', function ($collection) { - $collection->index( - 'username', - null, - null, - [ - 'sparse' => true, - 'unique' => true, - 'background' => true, - ] - ); - }); - -Inherited operations: - - -* create and drop -* collection -* hasCollection -* index and dropIndex (compound indexes supported as well) -* unique - -MongoDB specific operations: - - -* background -* sparse -* expire -* geospatial - -All other (unsupported) operations are implemented as dummy pass-through -methods because MongoDB does not use a predefined schema. - -Read more about the schema builder on `Laravel Docs `__ - -Geospatial indexes -~~~~~~~~~~~~~~~~~~ - -Geospatial indexes can improve query performance of location-based documents. - -They come in two forms: ``2d`` and ``2dsphere``. Use the schema builder to add -these to a collection. - -.. code-block:: php - - Schema::create('bars', function ($collection) { - $collection->geospatial('location', '2d'); - }); - -To add a ``2dsphere`` index: - -.. code-block:: php - - Schema::create('bars', function ($collection) { - $collection->geospatial('location', '2dsphere'); - }); - -Relationships -------------- - -Basic Usage -~~~~~~~~~~~ - -The only available relationships are: - - -* hasOne -* hasMany -* belongsTo -* belongsToMany - -The MongoDB-specific relationships are: - - -* embedsOne -* embedsMany - -Here is a small example: - -.. code-block:: php - - use MongoDB\Laravel\Eloquent\Model; - - class User extends Model - { - public function items() - { - return $this->hasMany(Item::class); - } - } - -The inverse relation of ``hasMany`` is ``belongsTo``: - -.. code-block:: php - - use MongoDB\Laravel\Eloquent\Model; - - class Item extends Model - { - public function user() - { - return $this->belongsTo(User::class); - } - } - -belongsToMany and pivots -~~~~~~~~~~~~~~~~~~~~~~~~ - -The belongsToMany relation will not use a pivot "table" but will push id's to -a **related_ids** attribute instead. This makes the second parameter for the -belongsToMany method useless. - -If you want to define custom keys for your relation, set it to ``null``: - -.. code-block:: php - - use MongoDB\Laravel\Eloquent\Model; - - class User extends Model - { - public function groups() - { - return $this->belongsToMany( - Group::class, null, 'user_ids', 'group_ids' - ); - } - } - -EmbedsMany Relationship -~~~~~~~~~~~~~~~~~~~~~~~ - -If you want to embed models, rather than referencing them, you can use the -``embedsMany`` relation. This relation is similar to the ``hasMany`` relation -but embeds the models inside the parent object. - -**REMEMBER**\ : These relations return Eloquent collections, they don't return -query builder objects! - -.. code-block:: php - - use MongoDB\Laravel\Eloquent\Model; - - class User extends Model - { - public function books() - { - return $this->embedsMany(Book::class); - } - } - -You can access the embedded models through the dynamic property: - -.. code-block:: php - - $user = User::first(); - - foreach ($user->books as $book) { - // - } - -The inverse relation is auto *magically* available. You can omit the reverse -relation definition. - -.. code-block:: php - - $book = Book::first(); - - $user = $book->user; - -Inserting and updating embedded models works similar to the ``hasMany`` relation: - -.. code-block:: php - - $book = $user->books()->save( - new Book(['title' => 'A Game of Thrones']) - ); - - // or - $book = - $user->books() - ->create(['title' => 'A Game of Thrones']); - -You can update embedded models using their ``save`` method (available since -release 2.0.0): - -.. code-block:: php - - $book = $user->books()->first(); - - $book->title = 'A Game of Thrones'; - $book->save(); - -You can remove an embedded model by using the ``destroy`` method on the -relation, or the ``delete`` method on the model (available since release 2.0.0): - -.. code-block:: php - - $book->delete(); - - // Similar operation - $user->books()->destroy($book); - -If you want to add or remove an embedded model, without touching the database, -you can use the ``associate`` and ``dissociate`` methods. - -To eventually write the changes to the database, save the parent object: - -.. code-block:: php - - $user->books()->associate($book); - $user->save(); - -Like other relations, embedsMany assumes the local key of the relationship -based on the model name. You can override the default local key by passing a -second argument to the embedsMany method: - -.. code-block:: php - - use MongoDB\Laravel\Eloquent\Model; - - class User extends Model - { - public function books() - { - return $this->embedsMany(Book::class, 'local_key'); - } - } - -Embedded relations will return a Collection of embedded items instead of a -query builder. Check out the available operations here: -`https://laravel.com/docs/master/collections `__ - -EmbedsOne Relationship -~~~~~~~~~~~~~~~~~~~~~~ - -The embedsOne relation is similar to the embedsMany relation, but only embeds a single model. - -.. code-block:: php - - use MongoDB\Laravel\Eloquent\Model; - - class Book extends Model - { - public function author() - { - return $this->embedsOne(Author::class); - } - } - -You can access the embedded models through the dynamic property: - -.. code-block:: php - - $book = Book::first(); - $author = $book->author; - -Inserting and updating embedded models works similar to the ``hasOne`` relation: - -.. code-block:: php - - $author = $book->author()->save( - new Author(['name' => 'John Doe']) - ); - - // Similar - $author = - $book->author() - ->create(['name' => 'John Doe']); - -You can update the embedded model using the ``save`` method (available since -release 2.0.0): - -.. code-block:: php - - $author = $book->author; - - $author->name = 'Jane Doe'; - $author->save(); - -You can replace the embedded model with a new model like this: - -.. code-block:: php - - $newAuthor = new Author(['name' => 'Jane Doe']); - - $book->author()->save($newAuthor); - -Cross-Database Relationships ----------------------------- - -If you're using a hybrid MongoDB and SQL setup, you can define relationships -across them. - -The model will automatically return a MongoDB-related or SQL-related relation -based on the type of the related model. - -If you want this functionality to work both ways, your SQL-models will need -to use the ``MongoDB\Laravel\Eloquent\HybridRelations`` trait. - -**This functionality only works for ``hasOne``, ``hasMany`` and ``belongsTo``.** - -The SQL model must use the ``HybridRelations`` trait: - -.. code-block:: php - - use MongoDB\Laravel\Eloquent\HybridRelations; - - class User extends Model - { - use HybridRelations; - - protected $connection = 'mysql'; - - public function messages() - { - return $this->hasMany(Message::class); - } - } - -Within your MongoDB model, you must define the following relationship: - -.. code-block:: php - - use MongoDB\Laravel\Eloquent\Model; - - class Message extends Model - { - protected $connection = 'mongodb'; - - public function user() - { - return $this->belongsTo(User::class); - } - } diff --git a/docs/eloquent-models/geo-index.txt b/docs/eloquent-models/geo-index.txt deleted file mode 100644 index fdca6b92a..000000000 --- a/docs/eloquent-models/geo-index.txt +++ /dev/null @@ -1,32 +0,0 @@ -.. _laravel-eloquent-model-geospatial-index: - -================== -Geospatial Indexes -================== - -.. facet:: - :name: genre - :values: tutorial - -.. meta:: - :keywords: php framework, odm, code example - -Geospatial indexes can improve query performance of location-based documents. - -They come in two forms: ``2d`` and ``2dsphere``. Use the schema builder to add -these to a collection. - -.. code-block:: php - - Schema::create('bars', function ($collection) { - $collection->geospatial('location', '2d'); - }); - -To add a ``2dsphere`` index: - -.. code-block:: php - - Schema::create('bars', function ($collection) { - $collection->geospatial('location', '2dsphere'); - }); - diff --git a/docs/eloquent-models/model-class.txt b/docs/eloquent-models/model-class.txt new file mode 100644 index 000000000..6d494fc3c --- /dev/null +++ b/docs/eloquent-models/model-class.txt @@ -0,0 +1,24 @@ +.. _laravel-eloquent-model-class: + +===================== +Eloquent Model Class +==================== + +.. facet:: + :name: genre + :values: tutorial + +.. meta:: + :keywords: php framework, odm, code example + +Overview +-------- + +The {+odm-long+} lets you work with MongoDB by using the Laravel Eloquent +object-relational mapper (ORM). + +This page will show how to extend a model, specify a custom collection, +specify fillable, casts, soft deletes, and prunable. + +It will also show how to extend an authenticatable model, but this content +may be moved to the Fundamentals > Authentication page in the future. diff --git a/docs/eloquent-models/relationships.txt b/docs/eloquent-models/relationships.txt index 69a56d03e..f615e407e 100644 --- a/docs/eloquent-models/relationships.txt +++ b/docs/eloquent-models/relationships.txt @@ -14,277 +14,11 @@ Eloquent Model Relationships Relationships ------------- -Basic Usage -~~~~~~~~~~~ +This section describes each of the Laravel Eloquent and MongoDB-specific +relationships that you can use and provides examples for hasOne, hasMany, +belongsTo, belongsToMany, embedsOne, and embedsMany. -The only available relationships are: +Each example will show, when applicable, how to define the relationships, +access the related models, save/create, destroy/delete, and associate/disassociate. -* hasOne -* hasMany -* belongsTo -* belongsToMany - -The MongoDB-specific relationships are: - - -* embedsOne -* embedsMany - -Here is a small example: - -.. code-block:: php - - use MongoDB\Laravel\Eloquent\Model; - - class User extends Model - { - public function items() - { - return $this->hasMany(Item::class); - } - } - -The inverse relation of ``hasMany`` is ``belongsTo``: - -.. code-block:: php - - use MongoDB\Laravel\Eloquent\Model; - - class Item extends Model - { - public function user() - { - return $this->belongsTo(User::class); - } - } - -belongsToMany and pivots -~~~~~~~~~~~~~~~~~~~~~~~~ - -The belongsToMany relation will not use a pivot "table" but will push id's to -a **related_ids** attribute instead. This makes the second parameter for the -belongsToMany method useless. - -If you want to define custom keys for your relation, set it to ``null``: - -.. code-block:: php - - use MongoDB\Laravel\Eloquent\Model; - - class User extends Model - { - public function groups() - { - return $this->belongsToMany( - Group::class, null, 'user_ids', 'group_ids' - ); - } - } - -EmbedsMany Relationship -~~~~~~~~~~~~~~~~~~~~~~~ - -If you want to embed models, rather than referencing them, you can use the -``embedsMany`` relation. This relation is similar to the ``hasMany`` relation -but embeds the models inside the parent object. - -**REMEMBER**\ : These relations return Eloquent collections, they don't return -query builder objects! - -.. code-block:: php - - use MongoDB\Laravel\Eloquent\Model; - - class User extends Model - { - public function books() - { - return $this->embedsMany(Book::class); - } - } - -You can access the embedded models through the dynamic property: - -.. code-block:: php - - $user = User::first(); - - foreach ($user->books as $book) { - // - } - -The inverse relation is auto *magically* available. You can omit the reverse -relation definition. - -.. code-block:: php - - $book = Book::first(); - - $user = $book->user; - -Inserting and updating embedded models works similar to the ``hasMany`` relation: - -.. code-block:: php - - $book = $user->books()->save( - new Book(['title' => 'A Game of Thrones']) - ); - - // or - $book = - $user->books() - ->create(['title' => 'A Game of Thrones']); - -You can update embedded models using their ``save`` method (available since -release 2.0.0): - -.. code-block:: php - - $book = $user->books()->first(); - - $book->title = 'A Game of Thrones'; - $book->save(); - -You can remove an embedded model by using the ``destroy`` method on the -relation, or the ``delete`` method on the model (available since release 2.0.0): - -.. code-block:: php - - $book->delete(); - - // Similar operation - $user->books()->destroy($book); - -If you want to add or remove an embedded model, without touching the database, -you can use the ``associate`` and ``dissociate`` methods. - -To eventually write the changes to the database, save the parent object: - -.. code-block:: php - - $user->books()->associate($book); - $user->save(); - -Like other relations, embedsMany assumes the local key of the relationship -based on the model name. You can override the default local key by passing a -second argument to the embedsMany method: - -.. code-block:: php - - use MongoDB\Laravel\Eloquent\Model; - - class User extends Model - { - public function books() - { - return $this->embedsMany(Book::class, 'local_key'); - } - } - -Embedded relations will return a Collection of embedded items instead of a -query builder. Check out the available operations here: -`https://laravel.com/docs/master/collections `__ - -EmbedsOne Relationship -~~~~~~~~~~~~~~~~~~~~~~ - -The embedsOne relation is similar to the embedsMany relation, but only embeds a single model. - -.. code-block:: php - - use MongoDB\Laravel\Eloquent\Model; - - class Book extends Model - { - public function author() - { - return $this->embedsOne(Author::class); - } - } - -You can access the embedded models through the dynamic property: - -.. code-block:: php - - $book = Book::first(); - $author = $book->author; - -Inserting and updating embedded models works similar to the ``hasOne`` relation: - -.. code-block:: php - - $author = $book->author()->save( - new Author(['name' => 'John Doe']) - ); - - // Similar - $author = - $book->author() - ->create(['name' => 'John Doe']); - -You can update the embedded model using the ``save`` method (available since -release 2.0.0): - -.. code-block:: php - - $author = $book->author; - - $author->name = 'Jane Doe'; - $author->save(); - -You can replace the embedded model with a new model like this: - -.. code-block:: php - - $newAuthor = new Author(['name' => 'Jane Doe']); - - $book->author()->save($newAuthor); - -Cross-Database Relationships ----------------------------- - -If you're using a hybrid MongoDB and SQL setup, you can define relationships -across them. - -The model will automatically return a MongoDB-related or SQL-related relation -based on the type of the related model. - -If you want this functionality to work both ways, your SQL-models will need -to use the ``MongoDB\Laravel\Eloquent\HybridRelations`` trait. - -**This functionality only works for ``hasOne``, ``hasMany`` and ``belongsTo``.** - -The SQL model must use the ``HybridRelations`` trait: - -.. code-block:: php - - use MongoDB\Laravel\Eloquent\HybridRelations; - - class User extends Model - { - use HybridRelations; - - protected $connection = 'mysql'; - - public function messages() - { - return $this->hasMany(Message::class); - } - } - -Within your MongoDB model, you must define the following relationship: - -.. code-block:: php - - use MongoDB\Laravel\Eloquent\Model; - - class Message extends Model - { - protected $connection = 'mongodb'; - - public function user() - { - return $this->belongsTo(User::class); - } - } diff --git a/docs/eloquent-models/schema-builder.txt b/docs/eloquent-models/schema-builder.txt index 8bfcfeccb..42553707f 100644 --- a/docs/eloquent-models/schema-builder.txt +++ b/docs/eloquent-models/schema-builder.txt @@ -4,55 +4,13 @@ Schema Builder ============== -The database driver also has (limited) schema builder support. You can -conveniently manipulate collections and set indexes. +This page will show how to use Laravel Schemas to manage indexes and show +examples of each of the following: -Basic Usage -~~~~~~~~~~~ +- create and drop (is this different from index and dropIndex?) +- collection (what does this method do?) +- determining column existence -.. code-block:: php +It will also provide info on the MongoDB specific operations and +geospatial indexes. - Schema::create('users', function ($collection) { - $collection->index('name'); - $collection->unique('email'); - }); - -You can also pass all the parameters specified :manual:`in the MongoDB docs ` -to the ``$options`` parameter: - -.. code-block:: php - - Schema::create('users', function ($collection) { - $collection->index( - 'username', - null, - null, - [ - 'sparse' => true, - 'unique' => true, - 'background' => true, - ] - ); - }); - -Inherited operations: - - -* create and drop -* collection -* hasCollection -* index and dropIndex (compound indexes supported as well) -* unique - -MongoDB specific operations: - - -* background -* sparse -* expire -* geospatial - -All other (unsupported) operations are implemented as dummy pass-through -methods because MongoDB does not use a predefined schema. - -Read more about the schema builder on `Laravel Docs `__ From 88b7ec73fc49ed15309ab10591b34d4b269e76e6 Mon Sep 17 00:00:00 2001 From: Chris Cho Date: Mon, 12 Feb 2024 14:54:20 -0500 Subject: [PATCH 04/23] rst fix --- docs/eloquent-models/model-class.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/eloquent-models/model-class.txt b/docs/eloquent-models/model-class.txt index 6d494fc3c..26edbc802 100644 --- a/docs/eloquent-models/model-class.txt +++ b/docs/eloquent-models/model-class.txt @@ -1,6 +1,6 @@ .. _laravel-eloquent-model-class: -===================== +==================== Eloquent Model Class ==================== From c57aaa07209f1aa020aa8e6faac9f5c8428da152 Mon Sep 17 00:00:00 2001 From: Chris Cho Date: Wed, 21 Feb 2024 17:47:28 -0500 Subject: [PATCH 05/23] Eloquent models Model Class page --- docs/eloquent-models.txt | 18 +- docs/eloquent-models/model-class.txt | 275 +++++++++++++++++- docs/eloquent-models/relationships.txt | 24 -- docs/eloquent-models/schema-builder.txt | 16 - .../eloquent-models/AuthenticatableUser.php | 10 + docs/includes/eloquent-models/Planet.php | 10 + .../eloquent-models/PlanetCollection.php | 10 + docs/includes/eloquent-models/PlanetDate.php | 12 + .../eloquent-models/PlanetMassAssignment.php | 10 + .../eloquent-models/PlanetMassPrune.php | 18 ++ .../eloquent-models/PlanetPrimaryKey.php | 10 + docs/includes/eloquent-models/PlanetPrune.php | 22 ++ .../eloquent-models/PlanetSoftDelete.php | 11 + 13 files changed, 389 insertions(+), 57 deletions(-) delete mode 100644 docs/eloquent-models/relationships.txt delete mode 100644 docs/eloquent-models/schema-builder.txt create mode 100644 docs/includes/eloquent-models/AuthenticatableUser.php create mode 100644 docs/includes/eloquent-models/Planet.php create mode 100644 docs/includes/eloquent-models/PlanetCollection.php create mode 100644 docs/includes/eloquent-models/PlanetDate.php create mode 100644 docs/includes/eloquent-models/PlanetMassAssignment.php create mode 100644 docs/includes/eloquent-models/PlanetMassPrune.php create mode 100644 docs/includes/eloquent-models/PlanetPrimaryKey.php create mode 100644 docs/includes/eloquent-models/PlanetPrune.php create mode 100644 docs/includes/eloquent-models/PlanetSoftDelete.php diff --git a/docs/eloquent-models.txt b/docs/eloquent-models.txt index c2267231f..2f28cac67 100644 --- a/docs/eloquent-models.txt +++ b/docs/eloquent-models.txt @@ -11,20 +11,18 @@ Eloquent Models .. meta:: :keywords: php framework, odm -This landing page will briefly describe Eloquent models and how -Laravel MongoDB extends it. This will be a landing page that identifies where -users can find information on a particular Eloquent model topic. +Eloquent models are part of the Laravel Eloquent object-relational +mapping (ORM) framework that enable you to work with a database by using +model classes. The {+odm-short+} extends this framework to use similar +syntax to work with MongoDB as a database. -Learn how to use Laravel Eloquent models in the {+odm-long+} to work with -MongoDB in the following sections: +This section contains guidance on how to use Eloquent models in +{+odm-short+} to work with MongoDB in the following ways: -- :ref:`laravel-eloquent-model-class` -- :ref:`laravel-eloquent-model-schema-builder` -- :ref:`laravel-eloquent-model-relationships` +- :ref:`laravel-eloquent-model-class` shows how to define models and customize + their behavior .. toctree:: /eloquent-models/model-class/ - /eloquent-models/schema-builder/ - /eloquent-models/relationships/ diff --git a/docs/eloquent-models/model-class.txt b/docs/eloquent-models/model-class.txt index 26edbc802..05ca89033 100644 --- a/docs/eloquent-models/model-class.txt +++ b/docs/eloquent-models/model-class.txt @@ -6,7 +6,7 @@ Eloquent Model Class .. facet:: :name: genre - :values: tutorial + :values: reference .. meta:: :keywords: php framework, odm, code example @@ -14,11 +14,272 @@ Eloquent Model Class Overview -------- -The {+odm-long+} lets you work with MongoDB by using the Laravel Eloquent -object-relational mapper (ORM). +In this guide, you can learn how to use the {+odm-long+} to define and +customize Laravel Eloquent models. You can use these models to work with +MongoDB data by using the Laravel Eloquent object-relational mapper (ORM). + +The following sections explain how to add Laravel Eloquent ORM behaviors +to {+odm-short+} models: + +- :ref:`laravel-model-define` shows how to create a + new model class +- :ref:`laravel-authenticatable-model` shows how to specify MongoDB as the + authentication user provider + Authenticatable : +- :ref:`laravel-model-customize` demonstrates several ways to customize the + moodel class behavior +- :ref:`laravel-model-pruning` shows how to periodically remove models that + you no longer need + + +.. _laravel-model-define: + +Define an Eloquent Model Class +------------------------------ + +Eloquent models are classes that represent your data. They include methods +that perform database operations such as inserts, updates, and deletes. + +To declare an {+odm-short+} model class, create a new file in your Laravel +application ``app/Models`` directory. Add the import for the +``MongoDB\Laravel\Eloquent\Model`` package and extend the ``Model`` class as +shown in the following code example: + +.. literalinclude:: /includes/eloquent-models/Planet.php + :language: php + :dedent: + +Alternatively, use the ``artisan`` console to generate the model and change +the ``Illuminate\Database\Eloquent\Model`` import to ``MongoDB\Laravel\Eloquent\Model``. +To learn more about the ``artisan`` console, see `Artisan Console `__ +in the Laravel docs. + +.. _laravel-authenticatable-model: + +Extend the Authenticatable Model +-------------------------------- + +To configure MongoDB as the Laravel user provider, you can extend the +{+odm-short+} `MongoDB\Laravel\Auth\User`` class. The following code example +shows how to extend this class: + +.. literalinclude:: /includes/eloquent-models/AuthenticatableUser.php + :language: php + :dedent: + +To learn more about customizing a Laravel authentication user provider, +see `Adding Custom User Providers `__ +in the Laravel docs. + +.. _laravel-model-customize: + +Customize an Eloquent Model Class +--------------------------------- + +This section shows how to perform the following Eloquent model customizations: + +- :ref:`laravel-model-customize-collection-name` +- :ref:`laravel-model-customize-primary-key` +- :ref:`laravel-model-soft-delete:` +- :ref:`laravel-model-cast-data-types` +- :ref:`laravel-model-mass-assignment` + +.. _laravel-model-customize-collection-name: + +Change the Model Collection Name +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +To customize the name of the collection the model uses to retrieve and save +data in MongoDB, override the ``$collection`` property of the model +class. + +By default, the model uses the MongoDB database name set in your Laravel +application's ``config/database.php`` setting and the snake case plural form of +your model class name for the collection. + +The following example specifies the custom MongoDB collection, ``celestial_body`` +for the ``Planet`` class: + +.. literalinclude:: /includes/eloquent-models/PlanetCollection.php + :language: php + :dedent: + +.. _laravel-model-customize-primary-key: + +Change the Primary Key Field +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +To customize the primary key field the model uses to uniquely identify a +MongoDB document, override the ``$primaryKey`` property of the model class. + +By default, the model uses the PHP MongoDB driver to generate unique IDs for +each document that your Laravel application inserts. + +The following example specifies the ``name`` field as the primary key for +the ``Planet`` class: + +.. literalinclude:: /includes/eloquent-models/PlanetPrimaryKey.php + :language: php + :dedent: + +To learn more about primary key behavior and customization options, see +`Eloquent Primary Keys `__ +in the Laravel docs. + +To learn more about the ``_id`` field and the MongoDB document structure, see +:manual:`Documents ` in the MongoDB server docs. + +.. _laravel-model-soft-delete: + +Enable Soft Deletes +~~~~~~~~~~~~~~~~~~~ + +Eloquent includes a soft delete feature which changes the behavior of the +``delete()`` method on a model. When soft delete is enabled, the ``delete()`` +method marks a document as deleted instead of removing it from the database. +It sets a timestamp on the ``deleted_at`` field to indicate that it should be +automatically excluded from retrieve operations. + +To enable soft deletes on a class, import the ``MongoDB\Laravel\Eloquent\SoftDeletes`` +package and add the trait to the class definition as shown in the following +code example: + +.. literalinclude:: /includes/eloquent-models/PlanetSoftDelete.php + :language: php + :dedent: + +To learn about methods you can perform on models with soft deletes enabled, see +`Eloquent Soft Deleting `__ +in the Laravel docs. + +.. _laravel-model-cast-data-types: + +Cast Data Types +--------------- + +Eloquent lets you convert model attribute data types before storing or +retrieving data by using an attribute casting helper. This helper is a +convenient alternative to defining equivalent accessor and mutator methods on +your model. + +In the following example, the casting helper converts the ``discovery_dt`` +model attribute, stored in MongoDB as a `MongoDB\BSON\UTCDateTime `__ +type, to the Laravel ``datetime`` type. + +.. literalinclude:: /includes/eloquent-models/PlanetDate.php + :language: php + :dedent: + +This conversion lets you use the PHP ``DateTime`` or the `Carbon class `__ +to work with dates in this field. The following example shows a Laravel +query that uses the casting helper on the model: + +.. code-block:: php + + Planet::where( + 'discovery_dt', '>', + new DateTime('3 years') + )->get(); + + +To learn more about MongoDB's data types, see :manual:`BSON Types ` +in the MongoDB server docs. + +to learn more about the Laravel casting helper abd supported types, see `Attribute Casting `__ +in the Laravel docs. + +.. _laravel-model-mass-assignment: + +Customize Mass Assignment +~~~~~~~~~~~~~~~~~~~~~~~~~ + +Eloquent lets you create several models and their attribute data by passing +an array of data to the ``create()`` model method. This process of inserting +multiple models is called mass assignment. + +Mass assignment can be an efficient way to create multiple models, but can +also be an exploitable security vulnerability. The data in the fields could +contain updates that could lead to unauthorized permissions or access. + +Eloquent providess the following traits to protect your data from mass +assignment vulnerabilities: + +- ``$fillable`` contains the fields that are set in a mass assignment +- ``$guarded`` contains the fields that are ignored in a mass assignment + +.. important:: + + We recommend using ``$fillable`` instead of ``$guarded`` to protect against + vulnerabilities. To learn more about this recommendation, see the + `Security Release: Laravel 6.18.35, 7.24.0 `__ + article on the Laravel site. + +In the following example, the model allows mass assignment of the fields +by using the ``$fillable`` attribute: + +.. literalinclude:: /includes/eloquent-models/PlanetMassAssignment.php + :language: php + :dedent: + +The following code example shows mass assignment of the ``Planet`` model: + +.. code-block:: php + + $planets = [ + [ 'name' => 'Earth', gravity => 9.8, day_length => '24 hours' ], + [ 'name' => 'Mars', gravity => 3.7, day_length => '25 hours' ], + ] + + Planet::create($planets); + +The models saved to the database contain only the ``name`` and ``gravity`` +fields since ``day_length`` was omitted from the ``$fillable`` attribute. + +To learn how to change the behavior when attempting to fill a field omitted +from the ``$fillable`` array, see `Mass Assignment Exceptions `__ +in the Laravel docs. + +.. _laravel-model-pruning + +Specify Pruning Behavior +------------------------ + +Eloquent lets you specify criteria by which to automatically delete model data +that you no longer need. When you schedule or run the ``model:prune`` command, +Laravel calls the ``prunable()`` method on all models that import the +``Prunable`` and ``MassPrunable`` traits to match the models for deletion. + +To use this feature with models that use MongoDB as a database, add the +appropriate import to your model: + +- ``MongoDB\Laravel\Eloquent\Prunable``: use this if you need + to perform cleanup when deleting a model that matches the criteria +- ``MongoDB\Laravel\Eloquent\MassPrunable``: use this if you do not need + to perform any cleanup when deleting a model that matches the criteria + +To learn more about the pruning feature, see `Pruning Models `__ +in the Laravel docs. + +Prunable Example +~~~~~~~~~~~~~~~~ + +The following example model shows how to perform a prune which calls the +``pruning()`` method prior to deleting a model that matches the query in the +``prunable()`` method:: + +.. literalinclude:: /includes/eloquent-models/PlanetPrune.php + :language: php + :dedent: + +Mass Prunable Example +~~~~~~~~~~~~~~~~~~~~~ + +The following example model shows how to perform a "mass prune" which deletes +all models that match the query in the ``prunable()`` method: + +.. literalinclude:: /includes/eloquent-models/PlanetMassPrune.php + :language: php + :dedent: + -This page will show how to extend a model, specify a custom collection, -specify fillable, casts, soft deletes, and prunable. -It will also show how to extend an authenticatable model, but this content -may be moved to the Fundamentals > Authentication page in the future. diff --git a/docs/eloquent-models/relationships.txt b/docs/eloquent-models/relationships.txt deleted file mode 100644 index f615e407e..000000000 --- a/docs/eloquent-models/relationships.txt +++ /dev/null @@ -1,24 +0,0 @@ -.. _laravel-eloquent-model-relationships: - -============================ -Eloquent Model Relationships -============================ - -.. facet:: - :name: genre - :values: tutorial - -.. meta:: - :keywords: php framework, odm, code example - -Relationships -------------- - -This section describes each of the Laravel Eloquent and MongoDB-specific -relationships that you can use and provides examples for hasOne, hasMany, -belongsTo, belongsToMany, embedsOne, and embedsMany. - -Each example will show, when applicable, how to define the relationships, -access the related models, save/create, destroy/delete, and associate/disassociate. - - diff --git a/docs/eloquent-models/schema-builder.txt b/docs/eloquent-models/schema-builder.txt deleted file mode 100644 index 42553707f..000000000 --- a/docs/eloquent-models/schema-builder.txt +++ /dev/null @@ -1,16 +0,0 @@ -.. _laravel-eloquent-model-schema-builder: - -============== -Schema Builder -============== - -This page will show how to use Laravel Schemas to manage indexes and show -examples of each of the following: - -- create and drop (is this different from index and dropIndex?) -- collection (what does this method do?) -- determining column existence - -It will also provide info on the MongoDB specific operations and -geospatial indexes. - diff --git a/docs/includes/eloquent-models/AuthenticatableUser.php b/docs/includes/eloquent-models/AuthenticatableUser.php new file mode 100644 index 000000000..5021b94eb --- /dev/null +++ b/docs/includes/eloquent-models/AuthenticatableUser.php @@ -0,0 +1,10 @@ + 'datetime', + ] +} diff --git a/docs/includes/eloquent-models/PlanetMassAssignment.php b/docs/includes/eloquent-models/PlanetMassAssignment.php new file mode 100644 index 000000000..b4acf23ff --- /dev/null +++ b/docs/includes/eloquent-models/PlanetMassAssignment.php @@ -0,0 +1,10 @@ +', 0.5); + } + +} diff --git a/docs/includes/eloquent-models/PlanetPrimaryKey.php b/docs/includes/eloquent-models/PlanetPrimaryKey.php new file mode 100644 index 000000000..761593941 --- /dev/null +++ b/docs/includes/eloquent-models/PlanetPrimaryKey.php @@ -0,0 +1,10 @@ + Date: Wed, 21 Feb 2024 17:55:52 -0500 Subject: [PATCH 06/23] grammar and spelling fixes --- docs/eloquent-models/model-class.txt | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/docs/eloquent-models/model-class.txt b/docs/eloquent-models/model-class.txt index 05ca89033..07b69ec88 100644 --- a/docs/eloquent-models/model-class.txt +++ b/docs/eloquent-models/model-class.txt @@ -9,7 +9,7 @@ Eloquent Model Class :values: reference .. meta:: - :keywords: php framework, odm, code example + :keywords: php framework, odm, code example, authentication, laravel Overview -------- @@ -27,7 +27,7 @@ to {+odm-short+} models: authentication user provider Authenticatable : - :ref:`laravel-model-customize` demonstrates several ways to customize the - moodel class behavior + model class behavior - :ref:`laravel-model-pruning` shows how to periodically remove models that you no longer need @@ -137,8 +137,8 @@ Enable Soft Deletes Eloquent includes a soft delete feature which changes the behavior of the ``delete()`` method on a model. When soft delete is enabled, the ``delete()`` method marks a document as deleted instead of removing it from the database. -It sets a timestamp on the ``deleted_at`` field to indicate that it should be -automatically excluded from retrieve operations. +It sets a timestamp on the ``deleted_at`` field to automatically exclude +it from retrieve operations. To enable soft deletes on a class, import the ``MongoDB\Laravel\Eloquent\SoftDeletes`` package and add the trait to the class definition as shown in the following @@ -185,7 +185,7 @@ query that uses the casting helper on the model: To learn more about MongoDB's data types, see :manual:`BSON Types ` in the MongoDB server docs. -to learn more about the Laravel casting helper abd supported types, see `Attribute Casting `__ +to learn more about the Laravel casting helper and supported types, see `Attribute Casting `__ in the Laravel docs. .. _laravel-model-mass-assignment: @@ -201,7 +201,7 @@ Mass assignment can be an efficient way to create multiple models, but can also be an exploitable security vulnerability. The data in the fields could contain updates that could lead to unauthorized permissions or access. -Eloquent providess the following traits to protect your data from mass +Eloquent provides the following traits to protect your data from mass assignment vulnerabilities: - ``$fillable`` contains the fields that are set in a mass assignment @@ -264,7 +264,7 @@ Prunable Example ~~~~~~~~~~~~~~~~ The following example model shows how to perform a prune which calls the -``pruning()`` method prior to deleting a model that matches the query in the +``pruning()`` method before deleting a model that matches the query in the ``prunable()`` method:: .. literalinclude:: /includes/eloquent-models/PlanetPrune.php @@ -281,5 +281,3 @@ all models that match the query in the ``prunable()`` method: :language: php :dedent: - - From fd48c620c6bd07eb9f8291ecd81240f7a09715e6 Mon Sep 17 00:00:00 2001 From: Chris Cho Date: Wed, 21 Feb 2024 17:57:55 -0500 Subject: [PATCH 07/23] rst fixes --- docs/eloquent-models/model-class.txt | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/eloquent-models/model-class.txt b/docs/eloquent-models/model-class.txt index 07b69ec88..e6270de86 100644 --- a/docs/eloquent-models/model-class.txt +++ b/docs/eloquent-models/model-class.txt @@ -60,7 +60,7 @@ Extend the Authenticatable Model -------------------------------- To configure MongoDB as the Laravel user provider, you can extend the -{+odm-short+} `MongoDB\Laravel\Auth\User`` class. The following code example +{+odm-short+} ``MongoDB\Laravel\Auth\User`` class. The following code example shows how to extend this class: .. literalinclude:: /includes/eloquent-models/AuthenticatableUser.php @@ -239,7 +239,7 @@ To learn how to change the behavior when attempting to fill a field omitted from the ``$fillable`` array, see `Mass Assignment Exceptions `__ in the Laravel docs. -.. _laravel-model-pruning +.. _laravel-model-pruning: Specify Pruning Behavior ------------------------ @@ -265,7 +265,7 @@ Prunable Example The following example model shows how to perform a prune which calls the ``pruning()`` method before deleting a model that matches the query in the -``prunable()`` method:: +``prunable()`` method: .. literalinclude:: /includes/eloquent-models/PlanetPrune.php :language: php From 4fa0cda890f13cf3ec16bacf3d54a9f58e2ad4a6 Mon Sep 17 00:00:00 2001 From: Chris Cho Date: Wed, 21 Feb 2024 18:02:54 -0500 Subject: [PATCH 08/23] rst fix --- docs/eloquent-models/model-class.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/eloquent-models/model-class.txt b/docs/eloquent-models/model-class.txt index e6270de86..327f6b3a8 100644 --- a/docs/eloquent-models/model-class.txt +++ b/docs/eloquent-models/model-class.txt @@ -80,7 +80,7 @@ This section shows how to perform the following Eloquent model customizations: - :ref:`laravel-model-customize-collection-name` - :ref:`laravel-model-customize-primary-key` -- :ref:`laravel-model-soft-delete:` +- :ref:`laravel-model-soft-delete` - :ref:`laravel-model-cast-data-types` - :ref:`laravel-model-mass-assignment` From 9c999f0b1dbb5ffb9e521dc8e35ab89d2c61d38e Mon Sep 17 00:00:00 2001 From: Chris Cho Date: Wed, 21 Feb 2024 18:38:57 -0500 Subject: [PATCH 09/23] tweaks --- docs/eloquent-models/model-class.txt | 89 ++++++++++--------- .../eloquent-models/PlanetMassAssignment.php | 2 +- 2 files changed, 47 insertions(+), 44 deletions(-) diff --git a/docs/eloquent-models/model-class.txt b/docs/eloquent-models/model-class.txt index 327f6b3a8..29076b9ab 100644 --- a/docs/eloquent-models/model-class.txt +++ b/docs/eloquent-models/model-class.txt @@ -14,23 +14,19 @@ Eloquent Model Class Overview -------- -In this guide, you can learn how to use the {+odm-long+} to define and +This guide shows you how to use the {+odm-long+} to define and customize Laravel Eloquent models. You can use these models to work with MongoDB data by using the Laravel Eloquent object-relational mapper (ORM). The following sections explain how to add Laravel Eloquent ORM behaviors to {+odm-short+} models: -- :ref:`laravel-model-define` shows how to create a - new model class -- :ref:`laravel-authenticatable-model` shows how to specify MongoDB as the - authentication user provider - Authenticatable : -- :ref:`laravel-model-customize` demonstrates several ways to customize the - model class behavior -- :ref:`laravel-model-pruning` shows how to periodically remove models that - you no longer need - +- :ref:`laravel-model-define` demonstrates how to create a model class. +- :ref:`laravel-authenticatable-model` shows how to set MongoDB as the + authentication user provider. +- :ref:`laravel-model-customize` explains several model class customizations +- :ref:`laravel-model-pruning` shows how to remove models that you no longer + need periodically. .. _laravel-model-define: @@ -40,7 +36,7 @@ Define an Eloquent Model Class Eloquent models are classes that represent your data. They include methods that perform database operations such as inserts, updates, and deletes. -To declare an {+odm-short+} model class, create a new file in your Laravel +To declare a {+odm-short+} model class, create a file in your Laravel application ``app/Models`` directory. Add the import for the ``MongoDB\Laravel\Eloquent\Model`` package and extend the ``Model`` class as shown in the following code example: @@ -49,8 +45,8 @@ shown in the following code example: :language: php :dedent: -Alternatively, use the ``artisan`` console to generate the model and change -the ``Illuminate\Database\Eloquent\Model`` import to ``MongoDB\Laravel\Eloquent\Model``. +Alternatively, use the ``artisan`` console to generate the model class and +change the ``Illuminate\Database\Eloquent\Model`` import to ``MongoDB\Laravel\Eloquent\Model``. To learn more about the ``artisan`` console, see `Artisan Console `__ in the Laravel docs. @@ -76,7 +72,8 @@ in the Laravel docs. Customize an Eloquent Model Class --------------------------------- -This section shows how to perform the following Eloquent model customizations: +This section shows how to perform the following Eloquent model behavior +customizations: - :ref:`laravel-model-customize-collection-name` - :ref:`laravel-model-customize-primary-key` @@ -97,11 +94,12 @@ By default, the model uses the MongoDB database name set in your Laravel application's ``config/database.php`` setting and the snake case plural form of your model class name for the collection. -The following example specifies the custom MongoDB collection, ``celestial_body`` -for the ``Planet`` class: +The following example specifies the custom MongoDB collection name, +``celestial_body``, for the ``Planet`` class: .. literalinclude:: /includes/eloquent-models/PlanetCollection.php :language: php + :emphasize-lines: 9 :dedent: .. _laravel-model-customize-primary-key: @@ -109,17 +107,18 @@ for the ``Planet`` class: Change the Primary Key Field ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -To customize the primary key field the model uses to uniquely identify a -MongoDB document, override the ``$primaryKey`` property of the model class. +To customize the model's primary key field that uniquely identify a MongoDB +document, override the ``$primaryKey`` property of the model class. By default, the model uses the PHP MongoDB driver to generate unique IDs for -each document that your Laravel application inserts. +each document your Laravel application inserts. The following example specifies the ``name`` field as the primary key for the ``Planet`` class: .. literalinclude:: /includes/eloquent-models/PlanetPrimaryKey.php :language: php + :emphasize-lines: 9 :dedent: To learn more about primary key behavior and customization options, see @@ -134,11 +133,11 @@ To learn more about the ``_id`` field and the MongoDB document structure, see Enable Soft Deletes ~~~~~~~~~~~~~~~~~~~ -Eloquent includes a soft delete feature which changes the behavior of the -``delete()`` method on a model. When soft delete is enabled, the ``delete()`` -method marks a document as deleted instead of removing it from the database. -It sets a timestamp on the ``deleted_at`` field to automatically exclude -it from retrieve operations. +Eloquent includes a soft delete feature that changes the behavior of the +``delete()`` method on a model. When soft delete is enabled on a model, the +``delete()`` method marks a document as deleted instead of removing it from the +database. It sets a timestamp on the ``deleted_at`` field to exclude it from +retrieve operations automatically. To enable soft deletes on a class, import the ``MongoDB\Laravel\Eloquent\SoftDeletes`` package and add the trait to the class definition as shown in the following @@ -146,6 +145,7 @@ code example: .. literalinclude:: /includes/eloquent-models/PlanetSoftDelete.php :language: php + :emphasize-lines: 6,10 :dedent: To learn about methods you can perform on models with soft deletes enabled, see @@ -163,16 +163,18 @@ convenient alternative to defining equivalent accessor and mutator methods on your model. In the following example, the casting helper converts the ``discovery_dt`` -model attribute, stored in MongoDB as a `MongoDB\BSON\UTCDateTime `__ +model attribute, stored in MongoDB as a `MongoDB\\BSON\\UTCDateTime `__ type, to the Laravel ``datetime`` type. .. literalinclude:: /includes/eloquent-models/PlanetDate.php :language: php + :emphasize-lines: 9-11 :dedent: -This conversion lets you use the PHP ``DateTime`` or the `Carbon class `__ -to work with dates in this field. The following example shows a Laravel -query that uses the casting helper on the model: +This conversion lets you use the PHP `DateTime `__ +or the `Carbon class `__ to work with dates +in this field. The following example shows a Laravel query that uses the +casting helper on the model: .. code-block:: php @@ -185,7 +187,7 @@ query that uses the casting helper on the model: To learn more about MongoDB's data types, see :manual:`BSON Types ` in the MongoDB server docs. -to learn more about the Laravel casting helper and supported types, see `Attribute Casting `__ +To learn more about the Laravel casting helper and supported types, see `Attribute Casting `__ in the Laravel docs. .. _laravel-model-mass-assignment: @@ -194,17 +196,17 @@ Customize Mass Assignment ~~~~~~~~~~~~~~~~~~~~~~~~~ Eloquent lets you create several models and their attribute data by passing -an array of data to the ``create()`` model method. This process of inserting +an array of data to the ``create()`` model method. This process of inserting multiple models is called mass assignment. -Mass assignment can be an efficient way to create multiple models, but can -also be an exploitable security vulnerability. The data in the fields could -contain updates that could lead to unauthorized permissions or access. +Mass assignment can be an efficient way to create multiple models. However, it +can be expose an exploitable security vulnerability. The data in the fields +could contain updates that could lead to unauthorized permissions or access. Eloquent provides the following traits to protect your data from mass assignment vulnerabilities: -- ``$fillable`` contains the fields that are set in a mass assignment +- ``$fillable`` contains the fields that are writeable in a mass assignment - ``$guarded`` contains the fields that are ignored in a mass assignment .. important:: @@ -219,6 +221,7 @@ by using the ``$fillable`` attribute: .. literalinclude:: /includes/eloquent-models/PlanetMassAssignment.php :language: php + :emphasize-lines: 9 :dedent: The following code example shows mass assignment of the ``Planet`` model: @@ -233,7 +236,7 @@ The following code example shows mass assignment of the ``Planet`` model: Planet::create($planets); The models saved to the database contain only the ``name`` and ``gravity`` -fields since ``day_length`` was omitted from the ``$fillable`` attribute. +fields since ``day_length`` is omitted from the ``$fillable`` attribute. To learn how to change the behavior when attempting to fill a field omitted from the ``$fillable`` array, see `Mass Assignment Exceptions `__ @@ -244,18 +247,18 @@ in the Laravel docs. Specify Pruning Behavior ------------------------ -Eloquent lets you specify criteria by which to automatically delete model data -that you no longer need. When you schedule or run the ``model:prune`` command, +Eloquent lets you specify criteria to delete model data that you no longer +need automatically. When you schedule or run the ``model:prune`` command, Laravel calls the ``prunable()`` method on all models that import the ``Prunable`` and ``MassPrunable`` traits to match the models for deletion. To use this feature with models that use MongoDB as a database, add the appropriate import to your model: -- ``MongoDB\Laravel\Eloquent\Prunable``: use this if you need - to perform cleanup when deleting a model that matches the criteria -- ``MongoDB\Laravel\Eloquent\MassPrunable``: use this if you do not need - to perform any cleanup when deleting a model that matches the criteria +- ``MongoDB\Laravel\Eloquent\Prunable`` optionally performs a cleanup + step before deleting a model that matches the criteria +- ``MongoDB\Laravel\Eloquent\MassPrunable`` deletes models that match the + criteria without fetching the model data To learn more about the pruning feature, see `Pruning Models `__ in the Laravel docs. @@ -263,7 +266,7 @@ in the Laravel docs. Prunable Example ~~~~~~~~~~~~~~~~ -The following example model shows how to perform a prune which calls the +The following example model shows how to perform a prune that calls the ``pruning()`` method before deleting a model that matches the query in the ``prunable()`` method: diff --git a/docs/includes/eloquent-models/PlanetMassAssignment.php b/docs/includes/eloquent-models/PlanetMassAssignment.php index b4acf23ff..fa8ffdc5f 100644 --- a/docs/includes/eloquent-models/PlanetMassAssignment.php +++ b/docs/includes/eloquent-models/PlanetMassAssignment.php @@ -6,5 +6,5 @@ class Planet extends Model { - $fillable = ['name', 'gravitational_force', 'diameter', 'number_of_moons']; + $fillable = ['name', 'gravitational_force', 'diameter', 'moons']; } From afda903eafbd8eda43228d6c612d7867c1733e34 Mon Sep 17 00:00:00 2001 From: Chris Cho Date: Wed, 21 Feb 2024 18:54:26 -0500 Subject: [PATCH 10/23] tweaks --- docs/eloquent-models/model-class.txt | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/eloquent-models/model-class.txt b/docs/eloquent-models/model-class.txt index 29076b9ab..2f258bf90 100644 --- a/docs/eloquent-models/model-class.txt +++ b/docs/eloquent-models/model-class.txt @@ -158,9 +158,8 @@ Cast Data Types --------------- Eloquent lets you convert model attribute data types before storing or -retrieving data by using an attribute casting helper. This helper is a -convenient alternative to defining equivalent accessor and mutator methods on -your model. +retrieving data by using a casting helper. This helper is a convenient +alternative to defining equivalent accessor and mutator methods on your model. In the following example, the casting helper converts the ``discovery_dt`` model attribute, stored in MongoDB as a `MongoDB\\BSON\\UTCDateTime `__ @@ -174,13 +173,14 @@ type, to the Laravel ``datetime`` type. This conversion lets you use the PHP `DateTime `__ or the `Carbon class `__ to work with dates in this field. The following example shows a Laravel query that uses the -casting helper on the model: +casting helper on the model to query for planets with a ``discovery_dt`` of +less than three years ago: .. code-block:: php Planet::where( 'discovery_dt', '>', - new DateTime('3 years') + new DateTime('-3 years') )->get(); @@ -231,7 +231,7 @@ The following code example shows mass assignment of the ``Planet`` model: $planets = [ [ 'name' => 'Earth', gravity => 9.8, day_length => '24 hours' ], [ 'name' => 'Mars', gravity => 3.7, day_length => '25 hours' ], - ] + ]; Planet::create($planets); From 6c2a80dc6ce2343559f3728bb660120f976323e7 Mon Sep 17 00:00:00 2001 From: Chris Cho Date: Wed, 21 Feb 2024 18:58:54 -0500 Subject: [PATCH 11/23] semicolon --- docs/includes/eloquent-models/PlanetDate.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/includes/eloquent-models/PlanetDate.php b/docs/includes/eloquent-models/PlanetDate.php index 52f77ce5c..bf372f965 100644 --- a/docs/includes/eloquent-models/PlanetDate.php +++ b/docs/includes/eloquent-models/PlanetDate.php @@ -8,5 +8,5 @@ class Planet extends Model { protected $casts = [ 'discovery_dt' => 'datetime', - ] + ]; } From 27635f4ee83dde3d0b7ecd4395b0be71972abdd0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=B4me=20Tamarelle?= Date: Thu, 22 Feb 2024 08:54:55 +0100 Subject: [PATCH 12/23] Apply CS fixes to the docs examples --- .../includes/eloquent-models/AuthenticatableUser.php | 3 --- docs/includes/eloquent-models/Planet.php | 1 - docs/includes/eloquent-models/PlanetCollection.php | 2 +- .../eloquent-models/PlanetMassAssignment.php | 12 +++++++++++- docs/includes/eloquent-models/PlanetMassPrune.php | 3 +-- phpcs.xml.dist | 12 ++++++++++++ 6 files changed, 25 insertions(+), 8 deletions(-) diff --git a/docs/includes/eloquent-models/AuthenticatableUser.php b/docs/includes/eloquent-models/AuthenticatableUser.php index 5021b94eb..be51dc9ce 100644 --- a/docs/includes/eloquent-models/AuthenticatableUser.php +++ b/docs/includes/eloquent-models/AuthenticatableUser.php @@ -2,9 +2,6 @@ namespace App\Models; -use MongoDB\Laravel\Auth\User; - class User extends Authenticatable { - } diff --git a/docs/includes/eloquent-models/Planet.php b/docs/includes/eloquent-models/Planet.php index f532ee26b..23f86f3c1 100644 --- a/docs/includes/eloquent-models/Planet.php +++ b/docs/includes/eloquent-models/Planet.php @@ -6,5 +6,4 @@ class Planet extends Model { - } diff --git a/docs/includes/eloquent-models/PlanetCollection.php b/docs/includes/eloquent-models/PlanetCollection.php index 04c74aeff..b36b24daa 100644 --- a/docs/includes/eloquent-models/PlanetCollection.php +++ b/docs/includes/eloquent-models/PlanetCollection.php @@ -6,5 +6,5 @@ class Planet extends Model { - $collection = 'celestial_body'; + protected $collection = 'celestial_body'; } diff --git a/docs/includes/eloquent-models/PlanetMassAssignment.php b/docs/includes/eloquent-models/PlanetMassAssignment.php index fa8ffdc5f..2a9b27d57 100644 --- a/docs/includes/eloquent-models/PlanetMassAssignment.php +++ b/docs/includes/eloquent-models/PlanetMassAssignment.php @@ -6,5 +6,15 @@ class Planet extends Model { - $fillable = ['name', 'gravitational_force', 'diameter', 'moons']; + /** + * The attributes that are mass assignable. + * + * @var array + */ + protected $fillable = [ + 'name', + 'gravitational_force', + 'diameter', + 'moons', + ]; } diff --git a/docs/includes/eloquent-models/PlanetMassPrune.php b/docs/includes/eloquent-models/PlanetMassPrune.php index 4a0e27edf..61b47b847 100644 --- a/docs/includes/eloquent-models/PlanetMassPrune.php +++ b/docs/includes/eloquent-models/PlanetMassPrune.php @@ -2,8 +2,8 @@ namespace App\Models; -use MongoDB\Laravel\Eloquent\Model; use MongoDB\Laravel\Eloquent\MassPrunable; +use MongoDB\Laravel\Eloquent\Model; class Planet extends Model { @@ -14,5 +14,4 @@ public function prunable() // matches models in which the solar_system field contains a null value return static::where('gravitational_force', '>', 0.5); } - } diff --git a/phpcs.xml.dist b/phpcs.xml.dist index 5f402d4ce..d7dd1e724 100644 --- a/phpcs.xml.dist +++ b/phpcs.xml.dist @@ -9,6 +9,7 @@ + docs src tests @@ -36,5 +37,16 @@ + + + + docs/**/*.php + + + docs/**/*.php + + + docs/**/*.php + From bcf9d7644f3c8dbeeb0f305e2dae495b1b34b182 Mon Sep 17 00:00:00 2001 From: Chris Cho Date: Thu, 22 Feb 2024 16:04:32 -0500 Subject: [PATCH 13/23] PRR fixes --- docs/eloquent-models/model-class.txt | 14 ++++++++++---- .../eloquent-models/AuthenticatableUser.php | 2 ++ .../eloquent-models/PlanetMassAssignment.php | 2 +- docs/includes/eloquent-models/PlanetMassPrune.php | 3 ++- docs/includes/eloquent-models/PlanetPrune.php | 3 ++- 5 files changed, 17 insertions(+), 7 deletions(-) diff --git a/docs/eloquent-models/model-class.txt b/docs/eloquent-models/model-class.txt index 2f258bf90..f2a2446c6 100644 --- a/docs/eloquent-models/model-class.txt +++ b/docs/eloquent-models/model-class.txt @@ -11,6 +11,12 @@ Eloquent Model Class .. meta:: :keywords: php framework, odm, code example, authentication, laravel +.. contents:: On this page + :local: + :backlinks: none + :depth: 2 + :class: singlecol + Overview -------- @@ -25,8 +31,8 @@ to {+odm-short+} models: - :ref:`laravel-authenticatable-model` shows how to set MongoDB as the authentication user provider. - :ref:`laravel-model-customize` explains several model class customizations -- :ref:`laravel-model-pruning` shows how to remove models that you no longer - need periodically. +- :ref:`laravel-model-pruning` shows how to periodically remove models that + you no longer need. .. _laravel-model-define: @@ -247,8 +253,8 @@ in the Laravel docs. Specify Pruning Behavior ------------------------ -Eloquent lets you specify criteria to delete model data that you no longer -need automatically. When you schedule or run the ``model:prune`` command, +Eloquent lets you specify criteria to periodically delete model data that you +no longer need. When you schedule or run the ``model:prune`` command, Laravel calls the ``prunable()`` method on all models that import the ``Prunable`` and ``MassPrunable`` traits to match the models for deletion. diff --git a/docs/includes/eloquent-models/AuthenticatableUser.php b/docs/includes/eloquent-models/AuthenticatableUser.php index be51dc9ce..694a595df 100644 --- a/docs/includes/eloquent-models/AuthenticatableUser.php +++ b/docs/includes/eloquent-models/AuthenticatableUser.php @@ -2,6 +2,8 @@ namespace App\Models; +use MongoDB\Laravel\Auth\User as Authenticatable; + class User extends Authenticatable { } diff --git a/docs/includes/eloquent-models/PlanetMassAssignment.php b/docs/includes/eloquent-models/PlanetMassAssignment.php index 2a9b27d57..3eeb4943f 100644 --- a/docs/includes/eloquent-models/PlanetMassAssignment.php +++ b/docs/includes/eloquent-models/PlanetMassAssignment.php @@ -7,7 +7,7 @@ class Planet extends Model { /** - * The attributes that are mass assignable. + * The mass assignable attributes. * * @var array */ diff --git a/docs/includes/eloquent-models/PlanetMassPrune.php b/docs/includes/eloquent-models/PlanetMassPrune.php index 61b47b847..f31ccc29a 100644 --- a/docs/includes/eloquent-models/PlanetMassPrune.php +++ b/docs/includes/eloquent-models/PlanetMassPrune.php @@ -11,7 +11,8 @@ class Planet extends Model public function prunable() { - // matches models in which the solar_system field contains a null value + // matches models in which the gravitational_force field contains + // a value greater than 0.5 return static::where('gravitational_force', '>', 0.5); } } diff --git a/docs/includes/eloquent-models/PlanetPrune.php b/docs/includes/eloquent-models/PlanetPrune.php index 666d134e6..1b1573076 100644 --- a/docs/includes/eloquent-models/PlanetPrune.php +++ b/docs/includes/eloquent-models/PlanetPrune.php @@ -17,6 +17,7 @@ public function prunable() protected function pruning() { - // delete photo assets of this model + // Cleanup cations such as deleting photo assets of this + // model or printing the Planet 'name' attribute to a log file } } From 5b5215d2d3e40c0d34ff90fe31925d70a5bc61e0 Mon Sep 17 00:00:00 2001 From: Chris Cho Date: Thu, 22 Feb 2024 16:18:03 -0500 Subject: [PATCH 14/23] fix code emphasis lines --- docs/eloquent-models/model-class.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/eloquent-models/model-class.txt b/docs/eloquent-models/model-class.txt index f2a2446c6..6c9b17ca2 100644 --- a/docs/eloquent-models/model-class.txt +++ b/docs/eloquent-models/model-class.txt @@ -30,7 +30,7 @@ to {+odm-short+} models: - :ref:`laravel-model-define` demonstrates how to create a model class. - :ref:`laravel-authenticatable-model` shows how to set MongoDB as the authentication user provider. -- :ref:`laravel-model-customize` explains several model class customizations +- :ref:`laravel-model-customize` explains several model class customizations. - :ref:`laravel-model-pruning` shows how to periodically remove models that you no longer need. @@ -227,7 +227,7 @@ by using the ``$fillable`` attribute: .. literalinclude:: /includes/eloquent-models/PlanetMassAssignment.php :language: php - :emphasize-lines: 9 + :emphasize-lines: 14-19 :dedent: The following code example shows mass assignment of the ``Planet`` model: From bc9796a88e19eb3582de51daeb4210872882d098 Mon Sep 17 00:00:00 2001 From: Chris Cho Date: Fri, 23 Feb 2024 17:09:21 -0500 Subject: [PATCH 15/23] PRR fixes --- docs/eloquent-models/model-class.txt | 91 ++++++++++++------- .../eloquent-models/PlanetMassAssignment.php | 5 - 2 files changed, 56 insertions(+), 40 deletions(-) diff --git a/docs/eloquent-models/model-class.txt b/docs/eloquent-models/model-class.txt index 6c9b17ca2..127cb5ea6 100644 --- a/docs/eloquent-models/model-class.txt +++ b/docs/eloquent-models/model-class.txt @@ -1,8 +1,3 @@ -.. _laravel-eloquent-model-class: - -==================== -Eloquent Model Class -==================== .. facet:: :name: genre @@ -42,19 +37,31 @@ Define an Eloquent Model Class Eloquent models are classes that represent your data. They include methods that perform database operations such as inserts, updates, and deletes. -To declare a {+odm-short+} model class, create a file in your Laravel -application ``app/Models`` directory. Add the import for the -``MongoDB\Laravel\Eloquent\Model`` package and extend the ``Model`` class as -shown in the following code example: +To declare a {+odm-short+} model, create a class in the ``app/Models`` +directory of your Laravel application that extends +``MongoDB\Laravel\Eloquent\Model`` as shown in the following code example: .. literalinclude:: /includes/eloquent-models/Planet.php :language: php + :emphasize-lines: 3,5,7 :dedent: -Alternatively, use the ``artisan`` console to generate the model class and -change the ``Illuminate\Database\Eloquent\Model`` import to ``MongoDB\Laravel\Eloquent\Model``. -To learn more about the ``artisan`` console, see `Artisan Console `__ -in the Laravel docs. +By default, the model uses the MongoDB database name set in your Laravel +application's ``config/database.php`` setting and the snake case plural +form of your model class name for the collection. + +This model is stored in the ``planets`` MongoDB collection. + +.. tip:: + + Alternatively, use the ``artisan`` console to generate the model class and + change the ``Illuminate\Database\Eloquent\Model`` import to ``MongoDB\Laravel\Eloquent\Model``. + To learn more about the ``artisan`` console, see `Artisan Console `__ + in the Laravel docs. + +To learn how to specify the database name that your Laravel application uses, +:ref:`laravel-quick-start-connect-to-mongodb`. + .. _laravel-authenticatable-model: @@ -92,13 +99,15 @@ customizations: Change the Model Collection Name ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -To customize the name of the collection the model uses to retrieve and save -data in MongoDB, override the ``$collection`` property of the model +By default, the model uses the snake case plural form of your model +class name. To change the name of the collection the model uses to retrieve +and save data in MongoDB, override the ``$collection`` property of the model class. -By default, the model uses the MongoDB database name set in your Laravel -application's ``config/database.php`` setting and the snake case plural form of -your model class name for the collection. +.. note:: + + We recommend using the default collection naming behavior to keep + the associations between models and collections straightforward. The following example specifies the custom MongoDB collection name, ``celestial_body``, for the ``Planet`` class: @@ -108,6 +117,10 @@ The following example specifies the custom MongoDB collection name, :emphasize-lines: 9 :dedent: +Without overriding the ``$collection`` property, this model maps to the +``planets`` collection. With the overridden property, the example class stores +the model in the ``celestial_body`` collection. + .. _laravel-model-customize-primary-key: Change the Primary Key Field @@ -116,8 +129,8 @@ Change the Primary Key Field To customize the model's primary key field that uniquely identify a MongoDB document, override the ``$primaryKey`` property of the model class. -By default, the model uses the PHP MongoDB driver to generate unique IDs for -each document your Laravel application inserts. +By default, the model uses the PHP MongoDB driver to generate unique ObjectIDs +for each document your Laravel application inserts. The following example specifies the ``name`` field as the primary key for the ``Planet`` class: @@ -131,8 +144,8 @@ To learn more about primary key behavior and customization options, see `Eloquent Primary Keys `__ in the Laravel docs. -To learn more about the ``_id`` field and the MongoDB document structure, see -:manual:`Documents ` in the MongoDB server docs. +To learn more about the ``_id`` field, ObjectIDs, and the MongoDB document +structure, see :manual:`Documents ` in the MongoDB server docs. .. _laravel-model-soft-delete: @@ -142,12 +155,11 @@ Enable Soft Deletes Eloquent includes a soft delete feature that changes the behavior of the ``delete()`` method on a model. When soft delete is enabled on a model, the ``delete()`` method marks a document as deleted instead of removing it from the -database. It sets a timestamp on the ``deleted_at`` field to exclude it from +database. It sets a timestamp on the ``deleted_at`` field to exclude it from retrieve operations automatically. -To enable soft deletes on a class, import the ``MongoDB\Laravel\Eloquent\SoftDeletes`` -package and add the trait to the class definition as shown in the following -code example: +To enable soft deletes on a class, add the ``MongoDB\Laravel\Eloquent\SoftDeletes`` +trait as shown in the following code example: .. literalinclude:: /includes/eloquent-models/PlanetSoftDelete.php :language: php @@ -206,8 +218,8 @@ an array of data to the ``create()`` model method. This process of inserting multiple models is called mass assignment. Mass assignment can be an efficient way to create multiple models. However, it -can be expose an exploitable security vulnerability. The data in the fields -could contain updates that could lead to unauthorized permissions or access. +can expose an exploitable security vulnerability. The data in the fields +might contain updates that lead to unauthorized permissions or access. Eloquent provides the following traits to protect your data from mass assignment vulnerabilities: @@ -227,7 +239,7 @@ by using the ``$fillable`` attribute: .. literalinclude:: /includes/eloquent-models/PlanetMassAssignment.php :language: php - :emphasize-lines: 14-19 + :emphasize-lines: 9-14 :dedent: The following code example shows mass assignment of the ``Planet`` model: @@ -254,7 +266,7 @@ Specify Pruning Behavior ------------------------ Eloquent lets you specify criteria to periodically delete model data that you -no longer need. When you schedule or run the ``model:prune`` command, +no longer need. When you schedule or run the ``model:prune`` command, Laravel calls the ``prunable()`` method on all models that import the ``Prunable`` and ``MassPrunable`` traits to match the models for deletion. @@ -266,15 +278,24 @@ appropriate import to your model: - ``MongoDB\Laravel\Eloquent\MassPrunable`` deletes models that match the criteria without fetching the model data +.. note:: + + When enabling soft deletes on a mass prunable model, you must import both + of the following {+odm-short+} packages: + + - ``MongoDB\Laravel\Eloquent\SoftDeletes`` + - ``MongoDB\Laravel\Eloquent\MassPrunable`` + + To learn more about the pruning feature, see `Pruning Models `__ in the Laravel docs. Prunable Example ~~~~~~~~~~~~~~~~ -The following example model shows how to perform a prune that calls the -``pruning()`` method before deleting a model that matches the query in the -``prunable()`` method: +The following prunable class includes a ``prunable()`` method that matches +models that the prune action deletes and a ``pruning()`` method that runs +before deleting a matching model: .. literalinclude:: /includes/eloquent-models/PlanetPrune.php :language: php @@ -283,8 +304,8 @@ The following example model shows how to perform a prune that calls the Mass Prunable Example ~~~~~~~~~~~~~~~~~~~~~ -The following example model shows how to perform a "mass prune" which deletes -all models that match the query in the ``prunable()`` method: +The following mass prunable class includes a ``prunable()`` method that matches +models that the prune action deletes: .. literalinclude:: /includes/eloquent-models/PlanetMassPrune.php :language: php diff --git a/docs/includes/eloquent-models/PlanetMassAssignment.php b/docs/includes/eloquent-models/PlanetMassAssignment.php index 3eeb4943f..b2a91cab1 100644 --- a/docs/includes/eloquent-models/PlanetMassAssignment.php +++ b/docs/includes/eloquent-models/PlanetMassAssignment.php @@ -6,11 +6,6 @@ class Planet extends Model { - /** - * The mass assignable attributes. - * - * @var array - */ protected $fillable = [ 'name', 'gravitational_force', From b454cfab15db7b8ac42c63c970e9041442a984c4 Mon Sep 17 00:00:00 2001 From: Chris Cho Date: Fri, 23 Feb 2024 17:30:18 -0500 Subject: [PATCH 16/23] fix header and highlighting --- docs/eloquent-models/model-class.txt | 8 ++++++++ docs/includes/eloquent-models/PlanetMassPrune.php | 2 +- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/docs/eloquent-models/model-class.txt b/docs/eloquent-models/model-class.txt index 127cb5ea6..6223c1cdf 100644 --- a/docs/eloquent-models/model-class.txt +++ b/docs/eloquent-models/model-class.txt @@ -1,3 +1,8 @@ +.. _laravel-eloquent-model-class: + +==================== +Eloquent Model Class +==================== .. facet:: :name: genre @@ -74,6 +79,7 @@ shows how to extend this class: .. literalinclude:: /includes/eloquent-models/AuthenticatableUser.php :language: php + :emphasize-lines: 3,5,7 :dedent: To learn more about customizing a Laravel authentication user provider, @@ -299,6 +305,7 @@ before deleting a matching model: .. literalinclude:: /includes/eloquent-models/PlanetPrune.php :language: php + :emphasize-lines: 6,10,12,18 :dedent: Mass Prunable Example @@ -309,5 +316,6 @@ models that the prune action deletes: .. literalinclude:: /includes/eloquent-models/PlanetMassPrune.php :language: php + :emphasize-lines: 6,10,12 :dedent: diff --git a/docs/includes/eloquent-models/PlanetMassPrune.php b/docs/includes/eloquent-models/PlanetMassPrune.php index f31ccc29a..15a309b43 100644 --- a/docs/includes/eloquent-models/PlanetMassPrune.php +++ b/docs/includes/eloquent-models/PlanetMassPrune.php @@ -2,8 +2,8 @@ namespace App\Models; -use MongoDB\Laravel\Eloquent\MassPrunable; use MongoDB\Laravel\Eloquent\Model; +use MongoDB\Laravel\Eloquent\MassPrunable; class Planet extends Model { From 4a28ba5a54d1d9559fe8a167e7c1c2aa7eadf8f0 Mon Sep 17 00:00:00 2001 From: ccho-mongodb Date: Fri, 23 Feb 2024 22:30:47 +0000 Subject: [PATCH 17/23] apply phpcbf formatting --- docs/includes/eloquent-models/PlanetMassPrune.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/includes/eloquent-models/PlanetMassPrune.php b/docs/includes/eloquent-models/PlanetMassPrune.php index 15a309b43..f31ccc29a 100644 --- a/docs/includes/eloquent-models/PlanetMassPrune.php +++ b/docs/includes/eloquent-models/PlanetMassPrune.php @@ -2,8 +2,8 @@ namespace App\Models; -use MongoDB\Laravel\Eloquent\Model; use MongoDB\Laravel\Eloquent\MassPrunable; +use MongoDB\Laravel\Eloquent\Model; class Planet extends Model { From 23139655fff4af80e74d52567c7fb90b062a6b4e Mon Sep 17 00:00:00 2001 From: Chris Cho Date: Fri, 23 Feb 2024 17:37:32 -0500 Subject: [PATCH 18/23] style guide fix --- docs/eloquent-models/model-class.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/eloquent-models/model-class.txt b/docs/eloquent-models/model-class.txt index 6223c1cdf..561264c65 100644 --- a/docs/eloquent-models/model-class.txt +++ b/docs/eloquent-models/model-class.txt @@ -286,8 +286,8 @@ appropriate import to your model: .. note:: - When enabling soft deletes on a mass prunable model, you must import both - of the following {+odm-short+} packages: + When enabling soft deletes on a mass prunable model, you must import the + following {+odm-short+} packages: - ``MongoDB\Laravel\Eloquent\SoftDeletes`` - ``MongoDB\Laravel\Eloquent\MassPrunable`` From 462e50013f1f1cfb2bd4977becc94bfd7b981857 Mon Sep 17 00:00:00 2001 From: Chris Cho Date: Fri, 23 Feb 2024 17:39:24 -0500 Subject: [PATCH 19/23] phpcbf highlighted line fix --- docs/eloquent-models/model-class.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/eloquent-models/model-class.txt b/docs/eloquent-models/model-class.txt index 561264c65..e8815720b 100644 --- a/docs/eloquent-models/model-class.txt +++ b/docs/eloquent-models/model-class.txt @@ -316,6 +316,6 @@ models that the prune action deletes: .. literalinclude:: /includes/eloquent-models/PlanetMassPrune.php :language: php - :emphasize-lines: 6,10,12 + :emphasize-lines: 5,10,12 :dedent: From 5fab20ac00e9e283e4a9b71b9907fc4162f9e1b8 Mon Sep 17 00:00:00 2001 From: Chris Cho Date: Fri, 23 Feb 2024 17:43:43 -0500 Subject: [PATCH 20/23] typo fix --- docs/includes/eloquent-models/PlanetPrune.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/includes/eloquent-models/PlanetPrune.php b/docs/includes/eloquent-models/PlanetPrune.php index 1b1573076..39d29152b 100644 --- a/docs/includes/eloquent-models/PlanetPrune.php +++ b/docs/includes/eloquent-models/PlanetPrune.php @@ -17,7 +17,7 @@ public function prunable() protected function pruning() { - // Cleanup cations such as deleting photo assets of this + // Add cleanup actions such as deleting photo assets of this // model or printing the Planet 'name' attribute to a log file } } From 7d7f6ef8a0e383b4615a74757e2e7599a4add499 Mon Sep 17 00:00:00 2001 From: Chris Cho Date: Fri, 23 Feb 2024 18:00:29 -0500 Subject: [PATCH 21/23] shorten comment --- docs/includes/eloquent-models/PlanetPrune.php | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/docs/includes/eloquent-models/PlanetPrune.php b/docs/includes/eloquent-models/PlanetPrune.php index 39d29152b..065a73d90 100644 --- a/docs/includes/eloquent-models/PlanetPrune.php +++ b/docs/includes/eloquent-models/PlanetPrune.php @@ -17,7 +17,6 @@ public function prunable() protected function pruning() { - // Add cleanup actions such as deleting photo assets of this - // model or printing the Planet 'name' attribute to a log file + // Add cleanup actions, such as logging the Planet 'name' attribute } } From fb6bc68b4df86f01379d74b7ffd1d6f5637471f8 Mon Sep 17 00:00:00 2001 From: Chris Cho Date: Wed, 28 Feb 2024 11:24:03 -0500 Subject: [PATCH 22/23] PRR fix --- docs/eloquent-models/model-class.txt | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/docs/eloquent-models/model-class.txt b/docs/eloquent-models/model-class.txt index e8815720b..cc779ac19 100644 --- a/docs/eloquent-models/model-class.txt +++ b/docs/eloquent-models/model-class.txt @@ -202,11 +202,7 @@ less than three years ago: .. code-block:: php - Planet::where( - 'discovery_dt', '>', - new DateTime('-3 years') - )->get(); - + Planet::where( 'discovery_dt', '>', new DateTime('-3 years'))->get(); To learn more about MongoDB's data types, see :manual:`BSON Types ` in the MongoDB server docs. From 49b08c24d39a824fd7119ecc454c04e52400a61e Mon Sep 17 00:00:00 2001 From: Chris Cho Date: Wed, 28 Feb 2024 11:35:42 -0500 Subject: [PATCH 23/23] PRR fixes --- docs/eloquent-models/model-class.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/eloquent-models/model-class.txt b/docs/eloquent-models/model-class.txt index cc779ac19..85b7b994b 100644 --- a/docs/eloquent-models/model-class.txt +++ b/docs/eloquent-models/model-class.txt @@ -132,7 +132,7 @@ the model in the ``celestial_body`` collection. Change the Primary Key Field ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -To customize the model's primary key field that uniquely identify a MongoDB +To customize the model's primary key field that uniquely identifies a MongoDB document, override the ``$primaryKey`` property of the model class. By default, the model uses the PHP MongoDB driver to generate unique ObjectIDs