### Install LdapRecord with Composer Source: https://ldaprecord.com/docs/core/v3/installation Run this command in your project's root directory to install the LdapRecord package via Composer. ```bash composer require directorytree/ldaprecord ``` -------------------------------- ### get Source: https://ldaprecord.com/docs/core/v3/searching-api Get all resulting entries of a query from the directory. Use `paginate` for more than 1000 entries. ```APIDOC ## `get` ### Description Get the resulting entries of a query from the directory: If you expect to have more than 1000 entries returned from your query, use the paginate method instead, which will return all entries. ### Method ```php $query->get() ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```php $query = $connection->query(); $entries = $query->where('company', '=', 'Acme')->get(); ``` ### Response #### Success Response (200) Returns a collection of LDAP entries matching the query criteria. #### Response Example ```php LdapRecord\Collection Object ``` ``` -------------------------------- ### Query Relationships with Constraints Source: https://ldaprecord.com/docs/core/v3/model-relationships Chain query builder methods like `whereStartsWith()` onto relationship methods to filter results before they are retrieved. This example fetches groups whose common name starts with 'Admin'. ```php $user = User::find('cn=John Doe,dc=local,dc=com'); $adminGroups = $user->groups()->whereStartsWith('cn', 'Admin')->get(); ``` -------------------------------- ### first Source: https://ldaprecord.com/docs/core/v3/searching-api Get the first resulting entry of a query from the directory. ```APIDOC ## `first` ### Description Get the first resulting entry of a query from the directory. ### Method ```php $query->first() ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```php $query = $connection->query(); $entry = $query->whereStartsWith('cn', 'Steve')->first(); ``` ### Response #### Success Response (200) Returns the first LDAP entry matching the query criteria, or `null` if no entries are found. #### Response Example ```php // If found: LdapRecord\Models\Model Object // If not found: null ``` ``` -------------------------------- ### Windows CA Certificate Configuration Source: https://ldaprecord.com/docs/core/v3/configuration Example of configuring the CA certificate path for Windows systems in ldap.conf. ```ini TLS_CACERT C:\\OpenLDAP\\sysconf\\ca.pem TLS_REQCERT hard ``` -------------------------------- ### Windows Integer Timestamp Example Source: https://ldaprecord.com/docs/core/v3/model-mutators An example of the 18-digit Active Directory timestamp format, also known as 'Windows NT time format' or 'Win32 FILETIME or SYSTEMTIME'. ```plaintext 132131246410000000 ``` -------------------------------- ### Find Model by GUID or Fail Source: https://ldaprecord.com/docs/core/v3/model-searching Retrieve a model by its string GUID, throwing a ModelNotFoundException if no match is found. This is useful when a GUID is expected to always exist. ```php use LdapRecord\Models\ActiveDirectory\User; $guid = 'f53c7b48-e8d1-425f-a23a-d1b98d7abfe8'; try { $user = User::findByGuidOrFail($guid); } catch ( \LdapRecord\Models\ModelNotFoundException $ex) { // Not found. } ``` -------------------------------- ### Search by Starting String Source: https://ldaprecord.com/docs/core/v3/searching Use the 'starts_with' operator or the startsWith() method to find LDAP entries where an attribute begins with a specified string. ```php $results = $query->where('cn', 'starts_with', 'John')->get(); // Or: $results = $query->whereStartsWith('cn', 'John')->get(); ``` -------------------------------- ### Import DistinguishedNameBuilder Source: https://ldaprecord.com/docs/core/v3/helpers Import the DistinguishedNameBuilder class to start building and transforming Distinguished Names. ```php use LdapRecord\Models\Attributes\DistinguishedNameBuilder; ``` -------------------------------- ### Long Chain Example Source: https://ldaprecord.com/docs/core/v3/helpers Demonstrates a complex chain of operations on a Distinguished Name. ```APIDOC ## Long Chain Example ### Description This example showcases chaining multiple methods for building and transforming a Distinguished Name. ### Example ```php $dn = DistinguishedName::of('cn=John Doe,dc=local,dc=com') ->shift(1, $removed) // Removes 'cn=John Doe', $removed = ['cn=John Doe'] ->prepend('ou', 'users') // Prepends 'ou=users' ->prepend($removed) // Prepends 'cn=John Doe' ->pop(1, $removed) // Removes the last RDN ('dc=com'), $removed = ['dc=com'] ->append('dc', 'org') // Appends 'dc=org' ->append($removed) // Appends 'dc=com' ->get(); // "cn=John Doe,ou=users,dc=local,dc=org,dc=com" echo $dn; ``` ``` -------------------------------- ### firstOrFail Source: https://ldaprecord.com/docs/core/v3/searching-api Get the first resulting entry of a query from the directory, or throw an exception if no entries are returned. ```APIDOC ## `firstOrFail` ### Description Get the first resulting entry of a query from the directory **or fail**. ### Method ```php $query->firstOrFail() ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```php $query = $connection->query(); try { $entry = $query->whereStartsWith('cn', 'Steve')->firstOrFail(); } catch (\\\LdapRecord\\\Models\\\ModelNotFoundException $ex) { // No entries returned. } ``` ### Response #### Success Response (200) Returns the first LDAP entry matching the query criteria. #### Response Example ```php LdapRecord\Models\Model Object ``` #### Error Response - **404 Not Found**: Throws `LdapRecord\Models\ModelNotFoundException` if no entries are returned. ``` -------------------------------- ### Linux/macOS CA Certificate Configuration Source: https://ldaprecord.com/docs/core/v3/configuration Example of configuring the CA certificate path for Linux and macOS systems in ldap.conf. ```ini TLS_CACERT /etc/ssl/certs/ca.pem TLS_REQCERT hard ``` -------------------------------- ### Has Many Relationship Filter Example Source: https://ldaprecord.com/docs/core/v3/model-relationships This shows an example of the LDAP filter constructed for a Has Many relationship, demonstrating how the user's DN is escaped and used to find related group objects. ```text (member=cn\3dJohn Doe\2cdc\3dacme\2cdc\3dorg) ``` -------------------------------- ### getGrammar Source: https://ldaprecord.com/docs/core/v3/searching-api Get the underlying query grammar instance. ```APIDOC ## `getGrammar` ### Description Get the underlying query grammar instance. ### Method ```php $query->getGrammar() ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```php $query = $connection->query(); // Returns instance of LdapRecord\Query\Grammar: $grammar = $query->getGrammar(); ``` ### Response #### Success Response (200) Returns the `LdapRecord\Query\Grammar` instance. #### Response Example ```php LdapRecord\Query\Grammar Object ``` ``` -------------------------------- ### Get the first resulting entry or fail Source: https://ldaprecord.com/docs/core/v3/searching-api Retrieves the first LDAP entry matching the query constraints. Throws a `ModelNotFoundException` if no entries are returned. ```php $query = $connection->query(); try { $entry = $query->whereStartsWith('cn', 'Steve')->first(); } catch (LdapRecordModelsModelNotFoundException $ex) { // Not entries returned. } ``` -------------------------------- ### components Source: https://ldaprecord.com/docs/core/v3/helpers Get all or specific components of the Distinguished Name. ```APIDOC ## components ### Description Get all of the components of the DN, or components of a specific type. ### Method `components(?string $type = null)` ### Parameters #### Path Parameters - **type** (string) - Optional - If provided, only components of this type (e.g., 'dc') will be returned. ### Response #### Success Response (array) - Returns an array of components. Each component is an array with two elements: the attribute type and its value. If a type is specified, returns only components of that type. ### Example ```php $dn = DistinguishedName::build('cn=john doe,ou=users,dc=local,dc=com'); // Get all components $dn->components(); // Returns: array:4 [ // 0 => array:2 [ // 0 => "cn" // 1 => "john doe" // ], // 1 => array:2 [ // 0 => "ou" // 1 => "users" // ], // 2 => array:2 [ // 0 => "dc" // 1 => "local" // ], // 3 => array:2 [ // 0 => "dc" // 1 => "com" // ] // ] // Get components of type 'dc' $dn->components('dc'); // Returns: array:2 [ // 0 => array:2 [ // 0 => "dc" // 1 => "local" // ], // 1 => array:2 [ // 0 => "dc" // 1 => "com" // ] // ] ``` ``` -------------------------------- ### Setting up DirectoryFake for Default Connection Source: https://ldaprecord.com/docs/core/v3/testing Swap the default LDAP connection with a fake using `DirectoryFake::setup()`. This allows you to add expectations and mock responses for testing. The fake connection instance is returned. ```php use LdapRecord\Testing\DirectoryFake; class LdapTest extends TestCase { public function test() { // Swap default connection with a fake... $fake = DirectoryFake::setup(); // Returns instanceof \LdapRecord\Testing\ConnectionFake // \LdapRecord\Container::getDefaultConnection(); // ... } } ``` -------------------------------- ### Get Binary Representation of GUID Source: https://ldaprecord.com/docs/core/v3/helpers Obtain the binary representation of a GUID by creating a `Guid` object and calling the `getBinary` method. ```php use LdapRecord\Models\Attributes\Guid; $guid = '270db4d0-249d-46a7-9cc5-eb695d9af9ac'; // "b"ð┤\r'Ø$ºF£┼Ùi]ܨ¼"" (new Guid($guid))->getBinary(); ``` -------------------------------- ### Get String Representation of GUID Source: https://ldaprecord.com/docs/core/v3/helpers Retrieve the original string value of a GUID by instantiating the `Guid` class and calling the `getValue` method. ```php use LdapRecord\Models\Attributes\Guid; $guid = '270db4d0-249d-46a7-9cc5-eb695d9af9ac'; // "270db4d0-249d-46a7-9cc5-eb695d9af9ac" (new Guid($guid))->getValue(); ``` -------------------------------- ### Configure LDAP Connection Source: https://ldaprecord.com/docs/core/v3/configuration Provides a comprehensive example of setting up an LDAP connection with both mandatory and optional parameters. Ensure you replace placeholder values with your actual LDAP server details. ```php use LdapRecord\Connection; $connection = new Connection([ // Mandatory Configuration Options 'hosts' => ['192.168.1.1'], 'base_dn' => 'dc=local,dc=com', 'username' => 'cn=admin,dc=local,dc=com', 'password' => 'password', // Optional Configuration Options 'port' => 389, 'protocol' => 'ldap://', 'use_ssl' => false, 'use_tls' => false, 'use_sasl' => false, 'version' => 3, 'timeout' => 5, 'follow_referrals' => false, // Custom LDAP Options 'options' => [ // See: http://php.net/ldap_set_option LDAP_OPT_X_TLS_REQUIRE_CERT => LDAP_OPT_X_TLS_HARD ], // See: https://www.php.net/manual/en/function.ldap-sasl-bind.php 'sasl_options' => [ 'mech' => null, 'realm' => null, 'authc_id' => null, 'authz_id' => null, 'props' => null, ], ]); ``` -------------------------------- ### Get Hexadecimal Representation of GUID Source: https://ldaprecord.com/docs/core/v3/helpers Instantiate the `Guid` class with a GUID string and use the `getHex` method to retrieve its hexadecimal representation. ```php use LdapRecord\Models\Attributes\Guid; $guid = '270db4d0-249d-46a7-9cc5-eb695d9af9ac'; // "d0b40d279d24a7469cc5eb695d9af9ac" (new Guid($guid))->getHex(); ``` -------------------------------- ### Setup Fake Directory Source: https://ldaprecord.com/docs/core/v3/testing-api Swap the default LdapRecord connection with a fake one for testing purposes. This should be called before your tests that require a mocked LDAP environment. ```php use LdapRecord\Testing\DirectoryFake; DirectoryFake::setup(); // LdapRecord\Testing\ConnectionFake ``` -------------------------------- ### Get Encoded Hexadecimal Representation of GUID Source: https://ldaprecord.com/docs/core/v3/helpers Use the `getEncodedHex` method on a `Guid` instance to obtain the GUID string with backslashes preceding each byte. ```php use LdapRecord\Models\Attributes\Guid; $guid = '270db4d0-249d-46a7-9cc5-eb695d9af9ac'; // "\d0\b4\0d\27\9d\24\a7\46\9c\c5\eb\69\5d\9a\f9\ac" (new Guid($guid))->getEncodedHex(); ``` -------------------------------- ### Get Converted GUID Source: https://ldaprecord.com/docs/core/v3/model-api Retrieves the model's GUID as a string. This is a formatted representation, not the raw binary. ```php // Example: bf9679e7-0de6-11d0-a285-00aa003049e2 $guid = $model->getConvertedGuid(); ``` -------------------------------- ### Long Chain Example for DN Manipulation Source: https://ldaprecord.com/docs/core/v3/helpers Demonstrates chaining multiple Distinguished Name building and transformation methods (`shift`, `prepend`, `pop`, `append`) in a single sequence. ```php $dn = DistinguishedName::of('cn=John Doe,dc=local,dc=com') ->shift(1, $removed) ->prepend('ou', 'users') ->prepend($removed) ->pop(1, $removed) ->append('dc', 'org') ->append($removed) ->get(); // "cn=John Doe,ou=users,dc=local,dc=org,dc=com" echo $dn; ``` -------------------------------- ### Decoded LDAP Filter Example Source: https://ldaprecord.com/docs/core/v3/model-scopes Shows the human-readable equivalent of the automatically escaped LDAP filter, illustrating the result of the escaping process. ```text (company=Acme Company) ``` -------------------------------- ### Setting up DirectoryFake for a Named Connection Source: https://ldaprecord.com/docs/core/v3/testing Swap a specific named LDAP connection with a fake using `DirectoryFake::setup('connectionName')`. This is useful when you have multiple connections configured and need to mock a particular one. ```php use LdapRecord\Testing\DirectoryFake; public function test() { $fake = DirectoryFake::setup('alpha'); // Returns instanceof \LdapRecord\Testing\ConnectionFake // \LdapRecord\Container::getConnection('alpha'); } ``` -------------------------------- ### Get Converted Object GUID Source: https://ldaprecord.com/docs/core/v3/models Retrieve the string representation of a model's Object GUID. This is useful for directories like Active Directory that store GUIDs as hexadecimal byte arrays. ```php $user = User::find('cn=user,dc=local,dc=com'); $user->getConvertedGuid(); ``` -------------------------------- ### fresh Source: https://ldaprecord.com/docs/core/v3/model-api Get a fresh **new** instance of the existing model. The model will be re-retrieved from the LDAP directory. The existing model will not be affected. ```APIDOC ## fresh ### Description Get a fresh **new** instance of the existing model. The model will be re-retrieved from the LDAP directory. The existing model will not be affected. ### Method ```php $fresh = $model->fresh(); ``` ``` -------------------------------- ### ConnectionFake::make Source: https://ldaprecord.com/docs/core/v3/testing-api Creates a new ConnectionFake instance with the provided configuration. ```APIDOC ## ConnectionFake::make ### Description Create a new `ConnectionFake` instance. ### Method Static method call ### Endpoint N/A (Static method) ### Parameters * **$config** (array) - Required - An array of configuration options for the fake connection. ### Request Example ```php use LdapRecord\Testing\ConnectionFake; $config = ['...']; $fake = ConnectionFake::make($config); ``` ### Response #### Success Response * **ConnectionFake** - An instance of `LdapRecord\Testing\ConnectionFake`. #### Response Example N/A ``` -------------------------------- ### Get Raw Object GUID Source: https://ldaprecord.com/docs/core/v3/model-api Retrieves the raw GUID of the object. Returns binary for Active Directory and string for other LDAP directories. ```php $rawBinary = $model->getObjectGuid(); ``` -------------------------------- ### Add 'whereStartsWith' Clause to Query Source: https://ldaprecord.com/docs/core/v3/searching-api Use this method to add a clause that searches for objects where an attribute starts with a specific value. The value is escaped by default. ```php $query = $connection->query(); // Returns "(cn=John*)" $query->whereStartsWith('cn', 'John')->getUnescapedQuery(); ``` -------------------------------- ### whereStartsWith Source: https://ldaprecord.com/docs/core/v3/searching-api Adds a clause to find objects where a specified attribute begins with a given value. This is useful for partial string matching at the beginning of an attribute's value. ```APIDOC ## whereStartsWith ### Description Adds a "starts with" clause to the query, searching for objects where the attribute starts with the given value. ### Method ```php whereStartsWith(string $attribute, string $value) ``` ### Example ```php $query = $connection->query(); // Returns "(cn=John*)" $query->whereStartsWith('cn', 'John')->getUnescapedQuery(); ``` ``` -------------------------------- ### Get GUID Key Attribute Source: https://ldaprecord.com/docs/core/v3/model-api Returns the name of the attribute key that stores the object's GUID. This is typically 'objectguid' but can be customized. ```php // Returns: 'objectguid' $model->getGuidKey(); ``` -------------------------------- ### Basic LdapRecord Usage Source: https://ldaprecord.com/docs/core/v3/quickstart Demonstrates how to create an LDAP connection, add it to the container, and perform common operations like retrieving all entries, finding a specific entry, accessing attributes, modifying attributes, and saving changes. ```php use LdapRecord\Container; use LdapRecord\Connection; use LdapRecord\Models\Entry; // Create a new connection: $connection = new Connection([ 'hosts' => ['192.168.1.1'], 'port' => 389, 'base_dn' => 'dc=local,dc=com', 'username' => 'cn=user,dc=local,dc=com', 'password' => 'secret', ]); // Add the connection into the container: Container::addConnection($connection); // Get all entries: $entries = Entry::get(); // Get a single entry: $entry = Entry::find('cn=John Doe,dc=local,dc=com'); // Getting attributes: foreach ($entry->memberof as $group) { echo $group; } // Modifying attributes: $entry->company = 'My Company'; // Saving changes: $entry->save(); ``` -------------------------------- ### Build Distinguished Name Source: https://ldaprecord.com/docs/core/v3/helpers Use `build` or its alias `of` to create a `DistinguishedName` builder. This can be used to construct DNs programmatically, either by pre-populating or starting from scratch. ```php $builder = DistinguishedName::build('cn=John Doe,dc=local,dc=com'); ``` ```php $builder = DistinguishedName::build(); ``` ```php $builder = DistinguishedName::of('cn=John Doe,dc=local,dc=com'); ``` ```php $builder = DistinguishedName::of(); ``` -------------------------------- ### Find Model by GUID Source: https://ldaprecord.com/docs/core/v3/model-searching Retrieve a model using its unique string GUID. Returns null if no model is found with the specified GUID. ```php use LdapRecord\Models\ActiveDirectory\User; $guid = 'f53c7b48-e8d1-425f-a23a-d1b98d7abfe8'; if ($user = User::findByGuid($guid)) { // Found user! } else { // Not found. } ``` -------------------------------- ### newInstance Source: https://ldaprecord.com/docs/core/v3/searching-api Creates a new query builder instance, optionally setting a new base DN. ```APIDOC ## newInstance ### Description Create a new query instance: ### Method ```php newInstance(?string $baseDn = null) ``` ### Parameters #### Path Parameters - **baseDn** (string|null) - Optional - The base Distinguished Name for the new query instance. Inherits from the current instance if not provided. ### Example ```php $query = $connection->query(); // Create and inherit the base DN from the previous instance: $newQuery = $query->newInstace(); // Use a new base DN: $newQuery = $query->newInstace('ou=Users,dc=local,dc=com'); ``` ``` -------------------------------- ### Add OR WHERE Not Starts With Clause Source: https://ldaprecord.com/docs/core/v3/searching-api Use `orWhereNotStartsWith` to add an 'or where not starts with' condition, excluding results where an attribute starts with a specific string. ```php // Returns "(!(cn=John*))" $connection->query() ->orWhereNotStartsWith('cn', 'John') ->getUnescapedQuery(); // Returns "(|" (!(cn=Suzy*))(!(cn=John*)))" $connection->query() ->whereNotStartsWith('cn', 'Suzy') ->orWhereNotStartsWith('cn', 'John') ->getUnescapedQuery(); ``` -------------------------------- ### GUID Utility Class Source: https://ldaprecord.com/docs/core/v3/helpers The GUID class provides static and instance methods for parsing, validating, and formatting Globally Unique Identifiers (GUIDs). ```APIDOC ## GUID A utility class for parsing and validating Object GUIDs. ```php use LdapRecord\Models\Attributes\Guid; ``` ### `isValid` Determine if a given string is a valid GUID: ```php // Returns "true" Guid::isValid('59e5e143-a50e-41a9-bf2b-badee699a577'); Guid::isValid('8be90b30-0bbb-4638-b468-7aaeb32c74f9'); Guid::isValid('17bab266-05ac-4e30-9fad-1c7093e4dd83'); // Returns "false" Guid::isValid('Invalid GUID'); Guid::isValid('17bab266-05ac-4e30-9fad'); Guid::isValid(''); ``` ### `getHex` Get the hexadecimal representation of the GUID string: ```php $guid = '270db4d0-249d-46a7-9cc5-eb695d9af9ac'; // "d0b40d279d24a7469cc5eb695d9af9ac" (new Guid($guid))->getHex(); ``` ### `getEncodedHex` Get the encoded hexadecimal representation of the GUID string: ```php $guid = '270db4d0-249d-46a7-9cc5-eb695d9af9ac'; // "\d0\b4\0d\27\9d\24\a7\46\9c\c5\eb\69\5d\9a\f9\ac" (new Guid($guid))->getEncodedHex(); ``` ### `getValue` Get the string representation of the GUID: ```php $guid = '270db4d0-249d-46a7-9cc5-eb695d9af9ac'; // "270db4d0-249d-46a7-9cc5-eb695d9af9ac" (new Guid($guid))->getValue(); ``` ### `getBinary` Get the binary representation of the GUID string: ```php $guid = '270db4d0-249d-46a7-9cc5-eb695d9af9ac'; // "b"ð┤\r'Ø$ºF£┼Ùi]ܨ¼"" (new Guid($guid))->getBinary(); ``` ``` -------------------------------- ### Define and Create an LDAP Connection Source: https://ldaprecord.com/docs/core/v3/connections Instantiate a new LDAP connection by providing your server details in the configuration array. Ensure all necessary parameters like hosts, username, and password are correctly set. ```php use LdapRecord\Connection; $connection = new Connection([ 'hosts' => ['192.168.1.1'], 'username' => 'cn=user,dc=local,dc=com', 'password' => 'secret', ]); ``` -------------------------------- ### Retrieve LDAP Model by Object GUID Source: https://ldaprecord.com/docs/core/v3/models Use `findByGuid()` with the model's object GUID to retrieve a specific record. The GUID must be in a valid format. ```php // Retrieve a model by its object guid... $user = User::findByGuid('bf9679e7-0de6-11d0-a285-00aa003049e2'); ``` -------------------------------- ### Use a Local Scope Source: https://ldaprecord.com/docs/core/v3/model-scopes Call the defined local scope directly on the model to apply its constraints to the query. This example retrieves all locked out users. ```php $usersLockedOut = User::lockedOut()->get(); ``` -------------------------------- ### Validate GUID String Source: https://ldaprecord.com/docs/core/v3/helpers Use the `isValid` static method to check if a given string conforms to the GUID format. It returns true for valid GUIDs and false for invalid ones. ```php use LdapRecord\Models\Attributes\Guid; // Returns "true" Guid::isValid('59e5e143-a50e-41a9-bf2b-badee699a577'); Guid::isValid('8be90b30-0bbb-4638-b468-7aaeb32c74f9'); Guid::isValid('17bab266-05ac-4e30-9fad-1c7093e4dd83'); // Returns "false" Guid::isValid('Invalid GUID'); Guid::isValid('17bab266-05ac-4e30-9fad'); Guid::isValid(''); ``` -------------------------------- ### newInstance Source: https://ldaprecord.com/docs/core/v3/model-api Creates a new, distinct model instance. ```APIDOC ## newInstance ### Description Create a **new** model instance. ### Method Not specified (assumed to be a method call on a model object) ### Endpoint Not applicable (SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```php $model = Model::findByAnr('sbauman'); $new = $model->newInstance(); ``` ### Response #### Success Response (200) Returns a new model instance. #### Response Example Not specified ``` -------------------------------- ### Retrieve First LDAP Model Source: https://ldaprecord.com/docs/core/v3/models Use `first()` to get the first model from a global LDAP search. Ensure the model class is correctly defined. ```php // Retrieve the first model of a global LDAP search... $user = User::first(); ``` -------------------------------- ### Registering a Closure Listener for Binding Events Source: https://ldaprecord.com/docs/core/v3/events Listen for the 'Binding' event and execute a closure to handle it. Access event details like connection, username, and password within the closure. ```php use LdapRecord\Container; use LdapRecord\Auth\Events\Binding; $dispatcher = Container::getDispatcher(); $dispatcher->listen(Binding::class, function (Binding $event) { $event->connection; // LdapRecord\Connections\Ldap instance $event->username; // 'jdoe@acme.org' $event->password; // 'super-secret' }); ``` -------------------------------- ### Get Distinguished Name Value Source: https://ldaprecord.com/docs/core/v3/helpers The `get` method retrieves the full string representation of the Distinguished Name. ```php $dn = DistinguishedName::make('cn=John Doe,dc=local,dc=com'); // "cn=John Doe,dc=local,dc=com" $dn->get(); ``` -------------------------------- ### select Source: https://ldaprecord.com/docs/core/v3/searching-api Set the attributes to return from the directory. By selecting only the attributes you need, you can effectively reduce memory usage on large query result sets. ```APIDOC ## select ### Description Set the attributes to return from the directory. By selecting only the attributes you need, you can effectively reduce memory usage on large query result sets. ### Method ```php $query->select(array $attributes) ``` ### Parameters #### Query Parameters - **attributes** (array) - Required - An array of attribute names to return. ### Example ```php $query = $connection->query(); // Only return the 'cn' and 'sn' attributes in result $query->select(['cn', 'sn'])->get(); ``` ``` -------------------------------- ### Connect to LDAP with Credentials Source: https://ldaprecord.com/docs/core/v3/authentication Use this snippet to establish a connection to your LDAP directory using a dedicated service account. Ensure you provide the correct host, base DN, username, and password. ```php $connection = new \LdapRecord\Connection([ 'hosts' => ['127.0.0.1'], 'base_dn' => 'dc=local,dc=com', 'username' => 'cn=WebApi,dc=local,dc=com', 'password' => 'super-secret', ]); $connection->connect(); ``` -------------------------------- ### orWhereStartsWith Source: https://ldaprecord.com/docs/core/v3/searching-api Adds an 'or where starts with' clause to the query. This allows filtering entries where a specific attribute starts with a given string. ```APIDOC ## orWhereStartsWith ### Description Adds an 'or where starts with' clause to the query. ### Method ```php $query->orWhereStartsWith(string $attribute, string $value) ``` ### Example ```php // Returns "(cn=John*)" $connection->query() ->orWhereStartsWith('cn', 'John') ->getUnescapedQuery(); // Returns "(|(cn=Suzy*)(cn=John*))" $connection->query() ->whereStartsWith('cn', 'Suzy') ->orWhereStartsWith('cn', 'John') ->getUnescapedQuery(); ``` ``` -------------------------------- ### Build and Execute a Simple Query Source: https://ldaprecord.com/docs/core/v3/searching Chain methods to build a query, filter by a common name, and retrieve results. ```php $results = $connection->query()->where('cn', '=', 'John Doe')->get(); ``` -------------------------------- ### Check for 'get' Mutator Source: https://ldaprecord.com/docs/core/v3/model-api Determine if a model has a 'get' mutator defined for a specific attribute. This is useful for custom attribute transformations. ```php class Entry extends Model { public function getCnAttribute(array $values): mixed { // ... } } $model = new Entry(); // Returns: true $model->hasGetMutator('cn'); ``` -------------------------------- ### Get All Groups Recursively Source: https://ldaprecord.com/docs/core/v3/active-directory/groups Retrieve all parent groups, including nested ones, that a group belongs to. Call `recursive()` before `get()`. ```php $group = Group::find('cn=Accounting,dc=local,dc=com'); $allGroups = $group->groups()->recursive()->get(); ``` -------------------------------- ### Mocking LDAP Bind Operations - Specific Calls Source: https://ldaprecord.com/docs/core/v3/testing Shows how to use `once()` to limit an expectation to a single call, allowing subsequent, different expectations to be reached for subsequent operations. ```php DirectoryFake::setup() ->getLdapConnection() ->expect([ LdapFake::operation('bind')->once()->with('cn=john,dc=local,dc=com')->andReturnResponse(), // ✅ Will be reached on subsequent bind attempt LdapFake::operation('bind')->once()->with('cn=jane,dc=local,dc=com')->andReturnResponse(), ]); ``` -------------------------------- ### Where Starts With Source: https://ldaprecord.com/docs/core/v3/searching Filters results to include only objects where a specified field begins with a given string. This can be achieved using the 'starts_with' operator or the dedicated `whereStartsWith()` method. ```APIDOC #### Where Starts With We could also perform a search for all objects beginning with the common name of 'John' using the `starts_with` operator: ```php $results = $query->where('cn', 'starts_with', 'John')->get(); // Or: $results = $query->whereStartsWith('cn', 'John')->get(); ``` ``` -------------------------------- ### Get Immediate Group Members Source: https://ldaprecord.com/docs/core/v3/active-directory/groups Retrieve the direct members of a group by calling the `members()` relationship and then `get()` on the group model instance. ```php $group = Group::find('cn=Accounting,dc=local,dc=com'); $members = $group->members()->get(); ``` -------------------------------- ### Create an Active Directory User Source: https://ldaprecord.com/docs/core/v3/active-directory/users This snippet shows how to create a new user in Active Directory, set essential attributes like common name, password, and account names, and then enable the user. It's recommended to encapsulate the save operation in a try-catch block to handle potential errors, such as password policy violations. ```php inside('ou=Users,dc=local,dc=com'); $user->cn = 'John Doe'; $user->unicodePwd = 'SecretPassword'; $user->samaccountname = 'jdoe'; $user->userPrincipalName = 'jdoe@acme.org'; $user->save(); // Sync the created users attributes. $user->refresh(); // Enable the user. $user->userAccountControl = 512; try { $user->save(); } catch (\ LdapRecord\LdapRecordException $e) { // Failed saving user. } ``` -------------------------------- ### Add 'or where starts with' clause Source: https://ldaprecord.com/docs/core/v3/searching-api Use `orWhereStartsWith` to add an 'or where starts with' clause to the query. This is useful for partial matching of string attributes. ```php // Returns "(cn=John*)" $connection->query() ->orWhereStartsWith('cn', 'John') ->getUnescapedQuery(); // Returns "(|(cn=Suzy*)(cn=John*))" $connection->query() ->whereStartsWith('cn', 'Suzy') ->orWhereStartsWith('cn', 'John') ->getUnescapedQuery(); ``` -------------------------------- ### Retrieve First LDAP Model or Fail Source: https://ldaprecord.com/docs/core/v3/models Use `firstOrFail()` to retrieve the first model or throw a `ModelNotFoundException`. This is useful for ensuring a record exists before proceeding. ```php // Retrieve the first model of a global LDAP search or fail... $user = User::firstOrFail(); ``` -------------------------------- ### Get All Group Members Recursively Source: https://ldaprecord.com/docs/core/v3/active-directory/groups To retrieve all members, including those in nested groups, use the `recursive()` method before calling `get()` on the `members()` relationship. ```php $group = Group::find('cn=Accounting,dc=local,dc=com'); $allMembers = $group->members()->recursive()->get(); ``` -------------------------------- ### DirectoryFake::setup Source: https://ldaprecord.com/docs/core/v3/testing-api Swaps the current LdapRecord\Connection in the Container with an LdapRecord\Testing\ConnectionFake. This is useful for mocking LDAP operations during testing. ```APIDOC ## DirectoryFake::setup ### Description Swaps the current `LdapRecord\Connection` in the `LdapRecord\Container` with an `LdapRecord\Testing\ConnectionFake`. ### Method Static method call ### Endpoint N/A (Static method) ### Parameters None ### Request Example ```php use LdapRecord\Testing\DirectoryFake; DirectoryFake::setup(); ``` ### Response #### Success Response N/A (Modifies container state) #### Response Example N/A ``` -------------------------------- ### Create Local Scopes with Parameters Source: https://ldaprecord.com/docs/core/v3/model-scopes Local scopes can accept additional parameters to further refine query constraints. This example adds a scope to filter users by a specific company. ```php // User.php public function scopeLockedOut(Builder $query): void { $query->where('lockouttime', '>', 1); } public function scopeCompany(Builder $query, $companyName): void { $query->where('company', '=', $companyName); } ``` -------------------------------- ### Set Up Caching Implementation Source: https://ldaprecord.com/docs/core/v3/caching Add your PSR-16 Simple Cache implementation to the LDAP connection instance using the setCache method. This is required before you can utilize query caching. ```php use LdapRecord\Connection; $connection = new Connection(['...']); $connection->setCache($myAppCache); ``` -------------------------------- ### Define Custom GUID Attribute Key Source: https://ldaprecord.com/docs/core/v3/models Configure a model to use a different attribute for storing GUIDs if your directory does not use 'objectguid'. Set the `$guidKey` property to the desired attribute name. ```php class User extends Model { protected string $guidKey = 'entryuuid'; } ``` -------------------------------- ### Connect to LDAP Server Source: https://ldaprecord.com/docs/core/v3/connections Establish a connection to your LDAP server using the `connect()` method on the connection instance. This method will attempt to bind to the server using the configured credentials. Handle potential `BindException` errors. ```php try { $connection->connect(); echo "Successfully connected!"; } catch (\ LdapRecord\Auth\BindException $e) { $error = $e->getDetailedError(); echo $error->getErrorCode(); echo $error->getErrorMessage(); echo $error->getDiagnosticMessage(); } ``` -------------------------------- ### Create New Model Instance Source: https://ldaprecord.com/docs/core/v3/model-api Instantiate a new, empty model object, typically used for creating new LDAP entries. ```php $model = Model::findByAnr('sbauman'); $new = $model->newInstance(); ``` -------------------------------- ### Retrieve LDAP Model by Object GUID or Fail Source: https://ldaprecord.com/docs/core/v3/models Use `findByGuidOrFail()` with the object GUID to retrieve a specific record or throw a `ModelNotFoundException`. This guarantees the record's existence via its unique identifier. ```php // Retrieve a model by its object guid or fail... $user = User::findByGuidOrFail('bf9679e7-0de6-11d0-a285-00aa003049e2'); ``` -------------------------------- ### findByGuid Source: https://ldaprecord.com/docs/core/v3/model-searching Find a model by its string GUID. ```APIDOC ## findByGuid ### Description Find a model by its string GUID. ### Method Not applicable (static method call on model). ### Endpoint Not applicable. ### Parameters - **guid** (string) - Required - The GUID of the model to find. ### Request Example ```php use LdapRecord\Models\ActiveDirectory\User; $guid = 'f53c7b48-e8d1-425f-a23a-d1b98d7abfe8'; if ($user = User::findByGuid($guid)) { // Found user! } ``` ### Response #### Success Response - **user** (Model|null) - The found user model instance or null if not found. ``` -------------------------------- ### Create a Company Scope Class Source: https://ldaprecord.com/docs/core/v3/model-scopes Implement the `LdapRecord\Models\Scope` interface to create a reusable global scope. The `apply` method receives the query builder and model, allowing you to add constraints. ```php where('company', '=', 'Acme Company'); } } ``` -------------------------------- ### getFilters Source: https://ldaprecord.com/docs/core/v3/searching-api Get the filters that have been added to the query. ```APIDOC ## `getFilters` ### Description Get the filters that have been added to the query. ### Method ```php $query->getFilters() ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```php $query = $connection->query(); $query->where('company', '=', 'Acme'); // array:3 [ // "and" => array:1 [ // 0 => array:3 [ // "field" => "company" // "operator" => "=" // "value" => LdapRecord\Models\Attributes\EscapedValue // ] // ] // "or" => [] // "raw" => [] // ] var_dump($query->getFilters()); ``` ### Response #### Success Response (200) Returns an array containing the query filters. #### Response Example ```php array( 'and' => array(...), 'or' => array(...), 'raw' => array(...) ) ``` ``` -------------------------------- ### getCache Source: https://ldaprecord.com/docs/core/v3/searching-api Get the query cache if it has been set. ```APIDOC ## `getCache` ### Description Get the query cache (if set). ### Method ```php $query->getCache() ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```php $query = $connection->query(); // Returns null or instance of LdapRecord\Query\Cache: $cache = $query->getCache(); ``` ### Response #### Success Response (200) Returns the query cache instance or `null` if no cache is set. #### Response Example ```php // If cache is set: LdapRecord\Query\Cache Object // If cache is not set: null ``` ``` -------------------------------- ### Create New Query Instance Source: https://ldaprecord.com/docs/core/v3/searching-api Creates a new query builder instance. It can inherit the base DN from the current instance or use a new one. ```php $query = $connection->query(); // Create and inherit the base DN from the previous instance: $newQuery = $query->newInstace(); // Use a new base DN: $newQuery = $query->newInstace('ou=Users,dc=local,dc=com'); ``` -------------------------------- ### findByGuidOrFail Source: https://ldaprecord.com/docs/core/v3/model-searching Find a model by its string GUID or fail. ```APIDOC ## findByGuidOrFail ### Description Find a model by its string GUID or fail. ### Method Not applicable (static method call on model). ### Endpoint Not applicable. ### Parameters - **guid** (string) - Required - The GUID of the model to find. ### Request Example ```php use LdapRecord\Models\ActiveDirectory\User; use LdapRecord\Models\ModelNotFoundException; $guid = 'f53c7b48-e8d1-425f-a23a-d1b98d7abfe8'; try { $user = User::findByGuidOrFail($guid); } catch (ModelNotFoundException $ex) { // Not found. } ``` ### Response #### Success Response - **user** (Model) - The found user model instance. #### Error Response - **404** - If the model is not found. ``` -------------------------------- ### Configure Fake Connection to be Connected Source: https://ldaprecord.com/docs/core/v3/testing-api Set the fake connection to bypass bind attempts and simulate a successful connection. Use the isConnected() method to verify the state. ```php $fake = ConnectionFake::make($config)->shouldBeConnected(); $fake->isConnected(); // true ``` -------------------------------- ### getConvertedGuid Source: https://ldaprecord.com/docs/core/v3/model-api Fetches the model's GUID in a string format. ```APIDOC ## getConvertedGuid ### Description Get the models string GUID. ### Method GET ### Endpoint `/models/{id}/guid/converted` (Conceptual) ### Parameters None ### Response #### Success Response (200) - **guid** (string) - The string representation of the model's GUID. ### Response Example ```json { "guid": "bf9679e7-0de6-11d0-a285-00aa003049e2" } ``` ``` -------------------------------- ### Registering a Class-Based Listener for Binding Events Source: https://ldaprecord.com/docs/core/v3/events Register a class to handle the 'Binding' event. The specified class must have a public 'handle' method that accepts the event object. ```php use LdapRecord\Container; use LdapRecord\Auth\Events\Binding; $dispatcher = Container::getDispatcher(); $dispatcher->listen(Binding::class, MyApp\BindingEventHandler::class); ``` -------------------------------- ### hasGetMutator Source: https://ldaprecord.com/docs/core/v3/model-api Checks if a 'get' mutator exists for the given attribute. ```APIDOC ## hasGetMutator ### Description Determine if the model has a 'get' mutator for the given attribute. ### Method Not specified (assumed to be a method call on a model object) ### Endpoint Not applicable (SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```php class Entry extends Model { public function getCnAttribute(array $values): mixed { // ... } } $model = new Entry(); // Returns: true $model->hasGetMutator('cn'); ``` ### Response #### Success Response (200) Returns `true` if a 'get' mutator exists, `false` otherwise. #### Response Example Not specified ``` -------------------------------- ### Retrieve a Fresh Model Instance Source: https://ldaprecord.com/docs/core/v3/models Fetches a new, up-to-date instance of a model from the directory without modifying the existing object. ```php $user = User::where('cn', '=', 'jdoe')->first(); $freshUser = $user->fresh(); ``` -------------------------------- ### getAnrAttributes Source: https://ldaprecord.com/docs/core/v3/model-api Get an array of ANR attributes defined on the model. ```APIDOC ## getAnrAttributes ### Description Get an array of ANR attributes defined on the model. ### Method ```php $attributes = $model->getAnrAttributes(); // Displays: // [ // 'cn', // 'sn', // 'uid', // 'name', // 'mail', // 'givenname', // 'displayname' // ] var_dump($attributes); ``` ``` -------------------------------- ### Create New Collection Instance Source: https://ldaprecord.com/docs/core/v3/model-api Generate a new `Tightenco\Collect\Support\Collection` instance, useful for managing arrays of data. ```php $collection = $model->newCollection($items = []); ``` -------------------------------- ### getQuery Source: https://ldaprecord.com/docs/core/v3/searching-api Get the raw, escaped LDAP query filter string. ```APIDOC ## `getQuery` ### Description Get the raw, **escaped** LDAP query filter. ### Method ```php $query->getQuery() ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```php $query = $connection->query(); $query->where('company', '=', 'Acme'); // Returns '(company=\41\63\6d\65)' $filter = $query->getQuery(); ``` ### Response #### Success Response (200) Returns the raw, escaped LDAP query filter string. #### Response Example ``` "(company=\41\63\6d\65)" ``` ``` -------------------------------- ### Listen for Model Creating Event Source: https://ldaprecord.com/docs/core/v3/models Retrieve the event dispatcher from the LdapRecord container and listen for the 'Creating' event on models. The listener receives the model instance via the event object. ```php listen(Creating::class, function ($event) { $model = $event->getModel(); }); ``` -------------------------------- ### getConnection Source: https://ldaprecord.com/docs/core/v3/searching-api Get the underlying LDAP connection instance the query is executing on. ```APIDOC ## `getConnection` ### Description Get the underlying connection the query is executing on. ### Method ```php $query->getConnection() ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```php $query = $connection->query(); // Returns instance of LdapRecord\Connection: $conn = $query->getConnection(); ``` ### Response #### Success Response (200) Returns the `LdapRecord\Connection` instance. #### Response Example ```php LdapRecord\Connection Object ``` ```