Overview
In this guide, you can learn how to set a read preference when performing find operations with Laravel MongoDB.
Before You Get Started
To run the code examples in this guide, complete the Quick Start tutorial. This tutorial provides instructions on setting up a MongoDB Atlas instance with sample data and creating the following files in your Laravel web application:
Movie.phpfile, which contains aMoviemodel to represent documents in themoviescollectionMovieController.phpfile, which contains ashow()function to run database operationsbrowse_movies.blade.phpfile, which contains HTML code to display the results of database operations
The following sections describe how to edit the files in your Laravel application to run the find operation code examples and view the expected output.
Set a Read Preference
To specify which replica set members receive your read operations, set a read preference by using the readPreference() method.
The readPreference() method accepts the following parameters:
mode: (Required) A string value specifying the read preference mode.tagSets: (Optional) An array value specifying key-value tags that correspond to certain replica set members.options: (Optional) An array value specifying additional read preference options.
Tip
To view a full list of available read preference modes and options, see MongoDB\Driver\ReadPreference::__construct in the MongoDB PHP extension documentation.
The following example queries for documents in which the value of the title field is "Carrie" and sets the read preference to ReadPreference::SECONDARY_PREFERRED. As a result, the query retrieves the results from secondary replica set members or the primary member if no secondaries are available:
Use the following syntax to specify the query:
$movies = Movie::where('title', 'Carrie') ->readPreference(ReadPreference::SECONDARY_PREFERRED) ->get();
To see the query results in the browse_movies view, edit the show() function in the MovieController.php file to resemble the following code:
class MovieController { public function show() { $movies = Movie::where('title', 'Carrie') ->readPreference(ReadPreference::SECONDARY_PREFERRED) ->get(); return view('browse_movies', [ 'movies' => $movies ]); } }
Additional Information
To learn how to retrieve data based on filter criteria, see the Retrieve MongoDB Data guide.
To learn how to modify the way that the Laravel Integration returns results, see the Modify Query Results guide.