Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[11.x] Introduce firstOrFail for Database Query Builder #51381

Closed
wants to merge 9 commits into from

Conversation

alnahian2003
Copy link
Contributor

Introduce firstOrFail for Database Query Builder:

This pull request introduces the firstOrFail method to the BuildsQueries class within Laravel's database query builder. This method mirrors the functionality of the existing firstOrFail method available in Eloquent models, providing a convenient way to retrieve the first result of a query or throw an exception if no record is found.

Benefits:

  • Improved Code Readability: Using firstOrFail in your database queries can enhance code readability and maintain consistency with Eloquent usage.
  • Reduced Boilerplate: This eliminates the need for explicit checks for null results followed by exception handling, streamlining your code.
  • Error Handling Consistency: It enforces consistent error handling in both database queries and Eloquent models.

Implementation Details:

  • The new firstOrFail method accepts two arguments:
    • $columns (optional): An array or string specifying the columns to select (defaults to '*').
    • $message (optional): A custom message to include in the thrown RecordNotFoundException.
  • The method first calls first($columns) to retrieve the first result.
  • If a result is found, it's returned directly.
  • If no record is found, a RecordNotFoundException is thrown with the provided message (or a default message if none is given).

Testing:

  • Two unit tests are included in DatabaseQueryBuilderTest:
    • testFirstOrFailMethodReturnsFirstResult verifies that the method correctly returns the first result when found.
    • testFirstOrFailMethodThrowsRecordNotFoundException ensures the method throws a RecordNotFoundException when no record exists.

Adoption:

Once merged, this method can be used directly in your database queries to retrieve the first result or gracefully handle situations where no record is found.

Example Usage:

$user = DB::table('flights')->firstOrFail();

// Or with where()
$user = DB::table('users')->where('id', 1)->firstOrFail();

// Or with a custom message
$post = DB::table('posts')->where('slug', 'my-post')->firstOrFail(message: 'No post found with that slug');

Thank You!

$builder->getConnection()->shouldReceive('select')->once()->with('select * from "users" where "id" = ? limit 1', [1], true)->andReturn([]);

$this->expectException(RecordNotFoundException::class);
$this->expectExceptionMessage("No record found for the given query.");
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

improve code style: (using single quotation)

$this->expectExceptionMessage('No record found for the given query.');

@saMahmoudzadeh
Copy link
Contributor

Hi @alnahian2003

Since you've added your pull request to version 11, it's better to also add [11.x] to the title.

@alnahian2003
Copy link
Contributor Author

Hi @alnahian2003

Since you've added your pull request to version 11, it's better to also add [11.x] to the title.

Thanks for the suggestion!

@alnahian2003 alnahian2003 changed the title Introduce firstOrFail for Database Query Builder [11.x] Introduce firstOrFail for Database Query Builder May 12, 2024
@taylorotwell
Copy link
Member

Thanks for your pull request to Laravel!

Unfortunately, I'm going to delay merging this code for now. To preserve our ability to adequately maintain the framework, we need to be very careful regarding the amount of code we include.

If possible, please consider releasing your code as a package so that the community can still take advantage of your contributions!

If you feel absolutely certain that this code corrects a bug in the framework, please "@" mention me in a follow-up comment with further explanation so that GitHub will send me a notification of your response.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

3 participants