Find First Or Throw

Meet the next generation of documentation. AI-native, beautiful, out-of-the-box, and built for developers and teams.

Purpose

The findFirstOrThrow method retrieves the first record that matches the provided criteria. It builds upon findFirst and guarantees a non-null result by throwing an exception when no records match. This makes it ideal for flows where missing data should be treated as an error.

Parameters

  • 'where' – Filter conditions.
  • 'orderBy' – Sorting rules applied before selecting the first record.
  • 'cursor' – Starting point for cursor-based pagination.
  • 'select' – Fields to include in the result.
  • 'include' – Related models to include.
  • 'distinct' – Ensures distinct results.
  • 'omit' – Fields to exclude from the result.

Return Value

Returns a single object if a matching record is found. If no record matches, an exception is thrown. This ensures the method never returns null.

Exception Handling

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

Features

  • Guarantees a returned record or fails immediately.
  • Supports all filtering, sorting, and include options of findFirst.
  • Prevents silent failures in critical flows.
  • Ideal for queries where missing data must 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

When no matching record exists, findFirstOrThrow immediately throws an exception. This behavior is ideal when the existence of the record is required.

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