findFirstOrThrow

Documentation for the findFirstOrThrow method, which retrieves the first User record matching the given filter criteria or throws an exception if no record is found.

Purpose

The findFirstOrThrow method is used to retrieve the first record that matches the given filter criteria. It builds upon findFirst and ensures a non-null result. If no record is found, an exception is thrown, making it useful in flows where a missing record should be considered an error.

Parameters

  • 'where' - An associative array specifying the filter conditions.
  • 'orderBy' - An associative array for sorting the results.
  • 'cursor' - Cursor-based pagination starting point.
  • 'select' - Fields to include in the returned object.
  • 'include' - Related models to include.
  • 'distinct' - Boolean to filter out duplicate results.
  • 'omit' - Fields to exclude from the result.

Return Value

Returns a single object of the specified model type. If no record matches the criteria, an exception is thrown. This ensures the result is never null.

Exception Handling

  • Throws an Exception if no record is found matching the provided criteria.
  • Throws an exception if both 'include' and 'select' are used together.
  • Throws an exception if 'where' is not an array or is empty when provided.
  • Throws an exception if invalid keys are found in the criteria array.

Features

  • Guarantees a result or fails fast with an exception.
  • Supports all filter, sort, and include options of findFirst.
  • Prevents silent failures when a missing record should trigger an error.

Example Usage

use Lib\Prisma\Classes\Prisma;

$prisma = Prisma::getInstance();

try {
    $user = $prisma->user->findFirstOrThrow([
        'where' => [
            'email' => [
                'equals' => 'john@example.com'
            ]
        ],
        'select' => [
            'id' => true,
            'name' => true,
            'email' => true
        ]
    ]);

    echo "<pre>"; print_r($user); echo "</pre>";
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}

Behavior When No Record Found

If no record matches the provided criteria, findFirstOrThrow will immediately throw an exception. This is useful when the existence of a record is mandatory for the flow:

try {
    $user = $prisma->user->findFirstOrThrow([
        'where' => ['id' => ['equals' => 123]]
    ]);
} catch (Exception $e) {
    echo "User not found.";
}