diff --git a/docs/compatibility.txt b/docs/compatibility.txt index fb253f888..fd3e2da02 100644 --- a/docs/compatibility.txt +++ b/docs/compatibility.txt @@ -15,7 +15,7 @@ Compatibility :class: singlecol .. meta:: - :keywords: laravel 9, laravel 10, laravel 11, 4.0, 4.1, 4.2, 5.0 + :keywords: laravel 9, laravel 10, laravel 11, 4.0, 4.1, 4.2, 5.0, 5.1 Laravel Compatibility --------------------- diff --git a/docs/eloquent-models.txt b/docs/eloquent-models.txt index 8aee6baf7..316313849 100644 --- a/docs/eloquent-models.txt +++ b/docs/eloquent-models.txt @@ -11,6 +11,12 @@ Eloquent Models .. meta:: :keywords: php framework, odm +.. toctree:: + + Eloquent Model Class + Relationships + Schema Builder + Eloquent models are part of the Laravel Eloquent object-relational mapping (ORM) framework, which lets you to work with data in a relational database by using model classes and Eloquent syntax. The {+odm-short+} extends @@ -26,9 +32,3 @@ the {+odm-short+} to work with MongoDB in the following ways: between models - :ref:`laravel-schema-builder` shows how to manage indexes on your MongoDB collections by using Laravel migrations - -.. toctree:: - - /eloquent-models/model-class/ - Relationships - Schema Builder diff --git a/docs/eloquent-models/model-class.txt b/docs/eloquent-models/model-class.txt index 4f81f4663..a2a9861bc 100644 --- a/docs/eloquent-models/model-class.txt +++ b/docs/eloquent-models/model-class.txt @@ -190,8 +190,8 @@ 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 `__ -type, to the Laravel ``datetime`` type. +model attribute, stored in MongoDB as a :php:`MongoDB\\BSON\\UTCDateTime +` type, to the Laravel ``datetime`` type. .. literalinclude:: /includes/eloquent-models/PlanetDate.php :language: php @@ -216,8 +216,8 @@ type, to the Laravel ``datetime`` type. To learn more, see `Attribute Casting `__ in the Laravel documentation. -This conversion lets you use the PHP `DateTime -`__ class to work with dates +This conversion lets you use the PHP :php:`DateTime +` class to work with dates in this field. The following example shows a Laravel query that uses the casting helper on the model to query for planets with a ``discovery_dt`` of less than three years ago: diff --git a/docs/fundamentals.txt b/docs/fundamentals.txt index f0945ad63..db482b2b8 100644 --- a/docs/fundamentals.txt +++ b/docs/fundamentals.txt @@ -15,11 +15,11 @@ Fundamentals :titlesonly: :maxdepth: 1 - /fundamentals/connection - /fundamentals/database-collection - /fundamentals/read-operations - /fundamentals/write-operations - /fundamentals/aggregation-builder + Connections + Databases & Collections + Read Operations + Write Operations + Aggregation Builder Learn more about the following concepts related to {+odm-long+}: diff --git a/docs/fundamentals/connection.txt b/docs/fundamentals/connection.txt index 26a937323..2434448ab 100644 --- a/docs/fundamentals/connection.txt +++ b/docs/fundamentals/connection.txt @@ -13,9 +13,9 @@ Connections .. toctree:: - /fundamentals/connection/connect-to-mongodb - /fundamentals/connection/connection-options - /fundamentals/connection/tls + Connection Guide + Connection Options + Configure TLS .. contents:: On this page :local: diff --git a/docs/fundamentals/connection/connect-to-mongodb.txt b/docs/fundamentals/connection/connect-to-mongodb.txt index d17bcf2be..f18d3b399 100644 --- a/docs/fundamentals/connection/connect-to-mongodb.txt +++ b/docs/fundamentals/connection/connect-to-mongodb.txt @@ -136,10 +136,8 @@ For a MongoDB database connection, you can specify the following details: 'host' => ['node1.example.com:27017', 'node2.example.com:27017', 'node3.example.com:27017'], - .. note:: - - This option does not accept hosts that use the DNS seedlist - connection format. + | This option does not accept hosts that use the DNS seedlist + connection format. * - ``database`` - Specifies the name of the MongoDB database to read and write to. diff --git a/docs/fundamentals/connection/tls.txt b/docs/fundamentals/connection/tls.txt index 793157286..9bf98248b 100644 --- a/docs/fundamentals/connection/tls.txt +++ b/docs/fundamentals/connection/tls.txt @@ -188,8 +188,9 @@ The following example configures a connection with TLS enabled: Additional Information ---------------------- -To learn more about setting URI options, see the `MongoDB\Driver\Manager::__construct() -`__ +To learn more about setting URI options, see the +:php:`MongoDB\\Driver\\Manager::__construct() +` API documentation. To learn more about enabling TLS on a connection, see the diff --git a/docs/includes/framework-compatibility-laravel.rst b/docs/includes/framework-compatibility-laravel.rst index bdfbd4d4c..16c405e21 100644 --- a/docs/includes/framework-compatibility-laravel.rst +++ b/docs/includes/framework-compatibility-laravel.rst @@ -7,7 +7,7 @@ - Laravel 10.x - Laravel 9.x - * - 4.2 to 5.0 + * - 4.2 to 5.1 - ✓ - ✓ - diff --git a/docs/includes/query-builder/QueryBuilderTest.php b/docs/includes/query-builder/QueryBuilderTest.php index 38f001a33..d99796fb2 100644 --- a/docs/includes/query-builder/QueryBuilderTest.php +++ b/docs/includes/query-builder/QueryBuilderTest.php @@ -48,6 +48,19 @@ protected function tearDown(): void parent::tearDown(); } + public function testOptions(): void + { + // begin options + $result = DB::connection('mongodb') + ->table('movies') + ->where('year', 2000) + ->options(['comment' => 'hello']) + ->get(); + // end options + + $this->assertInstanceOf(\Illuminate\Support\Collection::class, $result); + } + public function testWhere(): void { // begin query where diff --git a/docs/index.txt b/docs/index.txt index b767d4247..104a6aa77 100644 --- a/docs/index.txt +++ b/docs/index.txt @@ -13,21 +13,21 @@ :titlesonly: :maxdepth: 1 - /quick-start + Quick Start + Usage Examples Release Notes - /upgrade - /usage-examples - /fundamentals - /eloquent-models - /query-builder - /user-authentication - /cache - /queues - /transactions - /filesystems - /issues-and-help - /feature-compatibility - /compatibility + Fundamentals + Eloquent Models + Query Builder + User Authentication + Cache & Locks + Queues + Transactions + GridFS Filesystems + Issues & Help + Feature Compatibility + Compatibility + Upgrade Introduction ------------ diff --git a/docs/query-builder.txt b/docs/query-builder.txt index 2bb6f75f2..9bf4ea857 100644 --- a/docs/query-builder.txt +++ b/docs/query-builder.txt @@ -53,13 +53,16 @@ The following example shows the syntax of a query builder call: .. tip:: Set Database Connection - Before using the ``DB::table()`` method, ensure that you specify MongoDB as your application's - default database connection. For instructions on setting the database connection, - see the :ref:`laravel-quick-start-connect-to-mongodb` step in the Quick Start. + Before using the ``DB::table()`` method, ensure that you specify + MongoDB as your application's default database connection. For + instructions on setting the database connection, see the + :ref:`laravel-quick-start-connect-to-mongodb` step in the Quick + Start. - If MongoDB is not your application's default database, you can use the ``DB::connection()`` method - to specify a MongoDB connection. Pass the name of the connection to the ``connection()`` method, - as shown in the following code: + If MongoDB is not your application's default database, you can use + the ``DB::connection()`` method to specify a MongoDB connection. Pass + the name of the connection to the ``connection()`` method, as shown + in the following code: .. code-block:: php @@ -68,6 +71,7 @@ The following example shows the syntax of a query builder call: This guide provides examples of the following types of query builder operations: - :ref:`laravel-retrieve-query-builder` +- :ref:`laravel-options-query-builder` - :ref:`laravel-modify-results-query-builder` - :ref:`laravel-mongodb-read-query-builder` - :ref:`laravel-mongodb-write-query-builder` @@ -221,6 +225,13 @@ value greater than ``8.5`` and a ``year`` value of less than :start-after: begin query andWhere :end-before: end query andWhere +.. tip:: + + For compatibility with Laravel, Laravel MongoDB v5.1 supports both arrow + (``->``) and dot (``.``) notation to access nested fields in a query + filter. The preceding example uses dot notation to query the ``imdb.rating`` + nested field, which is the recommended syntax. + .. _laravel-query-builder-logical-not: Logical NOT Example @@ -647,6 +658,33 @@ value of ``imdb.rating`` of those matches by using the :start-after: begin aggregation with filter :end-before: end aggregation with filter +.. _laravel-options-query-builder: + +Set Query-Level Options +----------------------- + +You can modify the way that the {+odm-short+} performs operations by +setting options on the query builder. You can pass an array of options +to the ``options()`` query builder method to specify options for the +query. + +The following code demonstrates how to attach a comment to +a query: + +.. literalinclude:: /includes/query-builder/QueryBuilderTest.php + :language: php + :dedent: + :start-after: begin options + :end-before: end options + +The query builder accepts the same options that you can set for +the :phpmethod:`find() ` method in the +{+php-library+}. Some of the options to modify query results, such as +``skip``, ``sort``, and ``limit``, are settable directly as query +builder methods and are described in the +:ref:`laravel-modify-results-query-builder` section of this guide. We +recommend that you use these methods instead of passing them as options. + .. _laravel-modify-results-query-builder: Modify Query Results diff --git a/docs/queues.txt b/docs/queues.txt index 5e25d868b..951853084 100644 --- a/docs/queues.txt +++ b/docs/queues.txt @@ -11,6 +11,16 @@ Queues .. meta:: :keywords: php framework, odm, code example, jobs +Overview +-------- + +In this guide, you can learn how to use MongoDB as your database for +Laravel Queue. Laravel Queue allows you to create queued jobs that are +processed in the background. + +Configuration +------------- + To use MongoDB as your database for Laravel Queue, change the driver in your application's ``config/queue.php`` file: @@ -22,7 +32,7 @@ the driver in your application's ``config/queue.php`` file: // You can also specify your jobs-specific database // in the config/database.php file 'connection' => 'mongodb', - 'collection' => 'jobs', + 'table' => 'jobs', 'queue' => 'default', // Optional setting // 'retry_after' => 60, @@ -48,7 +58,7 @@ the behavior of the queue: ``mongodb`` connection. The driver uses the default connection if a connection is not specified. - * - ``collection`` + * - ``table`` - **Required** Name of the MongoDB collection to store jobs to process. @@ -60,7 +70,7 @@ the behavior of the queue: before retrying a job that is being processed. The value is ``60`` by default. -To use MongoDB to handle failed jobs, create a ``failed`` entry in your +To use MongoDB to handle *failed jobs*, create a ``failed`` entry in your application's ``config/queue.php`` file and specify the database and collection: @@ -69,7 +79,7 @@ collection: 'failed' => [ 'driver' => 'mongodb', 'database' => 'mongodb', - 'collection' => 'failed_jobs', + 'table' => 'failed_jobs', ], The following table describes properties that you can specify to configure @@ -86,21 +96,20 @@ how to handle failed jobs: - **Required** Queue driver to use. The value of this property must be ``mongodb``. - * - ``connection`` + * - ``database`` - Database connection used to store jobs. It must be a ``mongodb`` connection. The driver uses the default connection if a connection is not specified. - * - ``collection`` + * - ``table`` - Name of the MongoDB collection to store failed jobs. The value is ``failed_jobs`` by default. -Then, add the service provider in your application's -``config/app.php`` file: - -.. code-block:: php - - MongoDB\Laravel\MongoDBQueueServiceProvider::class, +To register failed jobs, you can use the default failed +job provider from Laravel. To learn more, see +`Dealing With Failed Jobs +`__ in +the Laravel documentation on Queues. Job Batching ------------ @@ -124,7 +133,7 @@ application's ``config/queue.php`` file: 'batching' => [ 'driver' => 'mongodb', 'database' => 'mongodb', - 'collection' => 'job_batches', + 'table' => 'job_batches', ], The following table describes properties that you can specify to configure @@ -141,18 +150,18 @@ job batching: - **Required** Queue driver to use. The value of this property must be ``mongodb``. - * - ``connection`` + * - ``database`` - Database connection used to store jobs. It must be a ``mongodb`` connection. The driver uses the default connection if a connection is not specified. - * - ``collection`` + * - ``table`` - Name of the MongoDB collection to store job batches. The value is ``job_batches`` by default. Then, add the service provider in your application's ``config/app.php`` file: -.. code-block:: php - - MongoDB\Laravel\MongoDBBusServiceProvider::class, +The {+odm-short+} automatically provides the +``MongoDB\Laravel\MongoDBBusServiceProvider::class`` class as the +service provider for job batching. diff --git a/docs/quick-start.txt b/docs/quick-start.txt index 39d8ba0b4..1d188ad84 100644 --- a/docs/quick-start.txt +++ b/docs/quick-start.txt @@ -17,6 +17,16 @@ Quick Start :depth: 1 :class: singlecol +.. toctree:: + + Download & Install + Create a Deployment + Create a Connection String + Configure Your Connection + View Data + Write Data + Next Steps + Overview -------- @@ -55,14 +65,3 @@ that connects to a MongoDB deployment. You can download the complete web application project by cloning the `laravel-quickstart `__ GitHub repository. - -.. toctree:: - - /quick-start/download-and-install/ - /quick-start/create-a-deployment/ - /quick-start/create-a-connection-string/ - /quick-start/configure-mongodb/ - /quick-start/view-data/ - /quick-start/write-data/ - /quick-start/next-steps/ - diff --git a/docs/quick-start/download-and-install.txt b/docs/quick-start/download-and-install.txt index 5e9139ec8..696861a43 100644 --- a/docs/quick-start/download-and-install.txt +++ b/docs/quick-start/download-and-install.txt @@ -28,6 +28,19 @@ Download and Install the Dependencies Complete the following steps to install and add the {+odm-short+} dependencies to a Laravel web application. +.. tip:: + + As an alternative to the following installation steps, you can use Laravel Herd + to install MongoDB and configure a Laravel MongoDB development environment. For + more information about using Laravel Herd with MongoDB, see the following resources: + + - `Installing MongoDB via Herd Pro + `__ in the Herd + documentation + - `Laravel Herd Adds Native MongoDB Support + `__ + in the MongoDB Developer Center + .. procedure:: :style: connected @@ -35,8 +48,8 @@ to a Laravel web application. {+odm-long+} requires the {+php-extension+} to manage MongoDB connections and commands. - Follow the `Installing the MongoDB PHP Driver with PECL `__ - guide to install the {+php-extension+}. + Follow the :php:`Installing the MongoDB PHP Driver with PECL + ` guide to install the {+php-extension+}. .. step:: Install Laravel diff --git a/docs/upgrade.txt b/docs/upgrade.txt index 3032b8e1e..a87d314a2 100644 --- a/docs/upgrade.txt +++ b/docs/upgrade.txt @@ -71,7 +71,7 @@ Version 5.x Breaking Changes This library version introduces the following breaking changes: -- The query builder returns results as as ``stdClass`` objects instead +- The query builder returns results as ``stdClass`` objects instead of as arrays. This change requires that you change array access to property access when interacting with query results. @@ -114,12 +114,19 @@ This library version introduces the following breaking changes: - In query results, the library converts BSON ``UTCDateTime`` objects to ``Carbon`` date classes, applying the default timezone. + In v5.1, the library also performs this conversion to the ``Model::raw()`` + method results before hydrating a Model instance. + - ``id`` is an alias for the ``_id`` field in MongoDB documents, and the library automatically converts between ``id`` and ``_id`` when querying data. The query result object includes an ``id`` field to represent the document's ``_id`` field. Because of this behavior, you cannot have two separate ``id`` and ``_id`` fields in your documents. + In v5.1, the library also performs this conversion to the ``Model::raw()`` + method results before hydrating a Model instance. When passing a complex query + filter, use the ``DB::where()`` method instead of ``Model::raw()``. + - Removes support for the ``$collection`` property. The following code shows how to assign a MongoDB collection to a variable in your ``User`` class in older versions compared to v5.0: diff --git a/docs/usage-examples.txt b/docs/usage-examples.txt index a17fd1b70..87a87df88 100644 --- a/docs/usage-examples.txt +++ b/docs/usage-examples.txt @@ -17,6 +17,22 @@ Usage Examples :depth: 2 :class: singlecol +.. toctree:: + :titlesonly: + :maxdepth: 1 + + Find a Document + Find Multiple Documents + Insert a Document + Insert Multiple Documents + Update a Document + Update Multiple Documents + Delete a Document + Delete Multiple Documents + Count Documents + Distinct Field Values + Run a Command + Overview -------- @@ -89,19 +105,3 @@ See code examples of the following operations in this section: - :ref:`laravel-count-usage` - :ref:`laravel-distinct-usage` - :ref:`laravel-run-command-usage` - -.. toctree:: - :titlesonly: - :maxdepth: 1 - - /usage-examples/findOne - /usage-examples/find - /usage-examples/insertOne - /usage-examples/insertMany - /usage-examples/updateOne - /usage-examples/updateMany - /usage-examples/deleteOne - /usage-examples/deleteMany - /usage-examples/count - /usage-examples/distinct - /usage-examples/runCommand diff --git a/phpstan.neon.dist b/phpstan.neon.dist index 539536a11..926d9e726 100644 --- a/phpstan.neon.dist +++ b/phpstan.neon.dist @@ -13,7 +13,7 @@ parameters: ignoreErrors: - '#Unsafe usage of new static#' - - '#Call to an undefined method [a-zA-Z0-9\\_\<\>]+::[a-zA-Z]+\(\)#' + - '#Call to an undefined method [a-zA-Z0-9\\_\<\>\(\)]+::[a-zA-Z]+\(\)#' services: errorFormatter.sarif: diff --git a/src/Connection.php b/src/Connection.php index 84ca97aba..592e500e5 100644 --- a/src/Connection.php +++ b/src/Connection.php @@ -217,6 +217,10 @@ protected function createConnection(string $dsn, array $config, array $options): $options['password'] = $config['password']; } + if (isset($config['name'])) { + $driverOptions += ['connectionName' => $config['name']]; + } + return new Client($dsn, $options, $driverOptions); } diff --git a/src/Eloquent/HybridRelations.php b/src/Eloquent/HybridRelations.php index 8ca4ea289..21344c8e9 100644 --- a/src/Eloquent/HybridRelations.php +++ b/src/Eloquent/HybridRelations.php @@ -334,15 +334,15 @@ public function belongsToMany( /** * Define a morph-to-many relationship. * - * @param string $related - * @param string $name - * @param null $table - * @param null $foreignPivotKey - * @param null $relatedPivotKey - * @param null $parentKey - * @param null $relatedKey - * @param null $relation - * @param bool $inverse + * @param class-string $related + * @param string $name + * @param string|null $table + * @param string|null $foreignPivotKey + * @param string|null $relatedPivotKey + * @param string|null $parentKey + * @param string|null $relatedKey + * @param string|null $relation + * @param bool $inverse * * @return \Illuminate\Database\Eloquent\Relations\MorphToMany */ @@ -410,13 +410,14 @@ public function morphToMany( /** * Define a polymorphic, inverse many-to-many relationship. * - * @param string $related - * @param string $name - * @param null $table - * @param null $foreignPivotKey - * @param null $relatedPivotKey - * @param null $parentKey - * @param null $relatedKey + * @param class-string $related + * @param string $name + * @param string|null $table + * @param string|null $foreignPivotKey + * @param string|null $relatedPivotKey + * @param string|null $parentKey + * @param string|null $relatedKey + * @param string|null $relation * * @return \Illuminate\Database\Eloquent\Relations\MorphToMany */ diff --git a/tests/ConnectionTest.php b/tests/ConnectionTest.php index fe3272943..1efd17be0 100644 --- a/tests/ConnectionTest.php +++ b/tests/ConnectionTest.php @@ -277,6 +277,34 @@ public function testQueryLog() } } + public function testQueryLogWithMultipleClients() + { + $connection = DB::connection('mongodb'); + $this->assertInstanceOf(Connection::class, $connection); + + // Create a second connection with the same config as the first + // Make sure to change the name as it's used as a connection identifier + $config = $connection->getConfig(); + $config['name'] = 'mongodb2'; + $secondConnection = new Connection($config); + + $connection->enableQueryLog(); + $secondConnection->enableQueryLog(); + + $this->assertCount(0, $connection->getQueryLog()); + $this->assertCount(0, $secondConnection->getQueryLog()); + + $connection->table('items')->get(); + + $this->assertCount(1, $connection->getQueryLog()); + $this->assertCount(0, $secondConnection->getQueryLog()); + + $secondConnection->table('items')->get(); + + $this->assertCount(1, $connection->getQueryLog()); + $this->assertCount(1, $secondConnection->getQueryLog()); + } + public function testDisableQueryLog() { // Disabled by default @@ -322,8 +350,8 @@ public function testPingMethod() 'dsn' => env('MONGODB_URI', 'mongodb://127.0.0.1/'), 'database' => 'unittest', 'options' => [ - 'connectTimeoutMS' => 100, - 'serverSelectionTimeoutMS' => 250, + 'connectTimeoutMS' => 1000, + 'serverSelectionTimeoutMS' => 6000, ], ]; diff --git a/tests/PHPStan/SarifErrorFormatter.php b/tests/PHPStan/SarifErrorFormatter.php index 92c0255cc..1e2ac7433 100644 --- a/tests/PHPStan/SarifErrorFormatter.php +++ b/tests/PHPStan/SarifErrorFormatter.php @@ -63,9 +63,6 @@ public function formatErrors(AnalysisResult $analysisResult, Output $output): in 'uri' => $this->relativePathHelper->getRelativePath($fileSpecificError->getFile()), 'uriBaseId' => self::URI_BASE_ID, ], - 'region' => [ - 'startLine' => $fileSpecificError->getLine(), - ], ], ], ], @@ -78,6 +75,10 @@ public function formatErrors(AnalysisResult $analysisResult, Output $output): in $result['properties']['tip'] = $fileSpecificError->getTip(); } + if ($fileSpecificError->getLine() !== null) { + $result['locations'][0]['physicalLocation']['region']['startLine'] = $fileSpecificError->getLine(); + } + $results[] = $result; } diff --git a/tests/config/database.php b/tests/config/database.php index 275dce61a..8a22d766c 100644 --- a/tests/config/database.php +++ b/tests/config/database.php @@ -10,8 +10,8 @@ 'dsn' => env('MONGODB_URI', 'mongodb://127.0.0.1/'), 'database' => env('MONGODB_DATABASE', 'unittest'), 'options' => [ - 'connectTimeoutMS' => 100, - 'serverSelectionTimeoutMS' => 250, + 'connectTimeoutMS' => 1000, + 'serverSelectionTimeoutMS' => 6000, ], ],