Skip to content

Commit

Permalink
firstOrFail on query builder
Browse files Browse the repository at this point in the history
  • Loading branch information
taylorotwell committed Sep 9, 2024
1 parent ce15abb commit ead13c7
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
19 changes: 19 additions & 0 deletions Concerns/BuildsQueries.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\MultipleRecordsFoundException;
use Illuminate\Database\Query\Expression;
use Illuminate\Database\RecordNotFoundException;
use Illuminate\Database\RecordsNotFoundException;
use Illuminate\Pagination\Cursor;
use Illuminate\Pagination\CursorPaginator;
Expand Down Expand Up @@ -343,6 +344,24 @@ public function first($columns = ['*'])
return $this->take(1)->get($columns)->first();
}

/**
* Execute the query and get the first result or throw an exception.
*
* @param array|string $columns
* @param string|null $message
* @return TValue
*
* @throws \Illuminate\Database\RecordNotFoundException
*/
public function firstOrFail($columns = ['*'], $message = null)
{
if (! is_null($result = $this->first($columns))) {
return $result;
}

throw new RecordNotFoundException($message ?: 'No record found for the given query.');
}

/**
* Execute the query and get the first result if it's the sole matching record.
*
Expand Down
10 changes: 10 additions & 0 deletions RecordNotFoundException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

namespace Illuminate\Database;

use RuntimeException;

class RecordNotFoundException extends RuntimeException
{
//
}

0 comments on commit ead13c7

Please sign in to comment.