Laravel Checking If a Record Exists
It depends if you want to work with the user afterwards or only check if one exists.
If you want to use the user object if it exists:
$user = User::where('email', '=', Input::get('email'))->first();
if ($user === null) {
// user doesn't exist
}
And if you only want to check
if (User::where('email', '=', Input::get('email'))->count() > 0) {
// user found
}
Or even nicer
if (User::where('email', '=', Input::get('email'))->exists()) {
// user found
}
Laravel 5.8 Eloquent check if record exists
Laravel's Query Builder has various aggregate methods, one of which is the exists()
method wherein you can check if a record exists or not.
//returns true or false
$checker = Purchase::select('id')->where('id',$request->itemid)->exists();
Here's the documentation link for reference:
- From Laravel 5.6 to 7.x
- Laravel 8
Checking if record exists in Laravel not working
The firstOrCreate method will attempt to locate a database record using the given column / value pairs. If the model can not be found in the database, a record will be inserted with the attributes resulting from merging the first array argument with the optional second array argument:
https://laravel.com/docs/8.x/eloquent#retrieving-or-creating-models
Check if record exists while registering user
Try the method withErrors()
:
Redirect::back()->withErrors(['warning', 'We could not find the company']);
I however recommend you to use the validation rule Exists
instead of having more queries and manually return a message. You can do it like so:
$request->validate([
'company_id' => 'required|integer|exists:App\Company,id',
]);
Then you won't need the extra logic and the other method.
Source: https://laravel.com/docs/7.x/validation#rule-exists
Check if the request record exists in the method show()
If you would like to change the error response, you can override the Exception Hander. To do this, add the following to the register
method in your your app/Exceptions/Handler.php
file:
$this->renderable(function (NotFoundHttpException $e, $request) {
$previous = $e->getPrevious();
if (
$previous instanceof ModelNotFoundException &&
$previous->getModel() === Font::class &&
$request->expectsJson()
) {
return response()->json(['message' => 'Not found'], 404);
}
});
Don't forget to import the necessary classes are the top:
use App\Models\Font;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
Alternatively, you could remove route model binding for this method (the easiest way to do this would be to remove the Font
type hint) and manually try to find
the model.
Related Topics
PHP PHP_Network_Getaddresses: Getaddrinfo Failed: No Such Host Is Known
PHP Preg_Match (.*) Not Matching Past Line Breaks
Session Unset, or Session_Destroy
Error: MySQLnd Cannot Connect to MySQL 4.1+ Using the Old Insecure Authentication
Colorizing Windows Command Line Output from PHP
How to Display an Blob Image Stored in MySQL Database
Laravel 4 Custom Named Password Column
PHP Mail Special Characters Utf8
Using MySQL Concat() in Where Clause
How to Add Private Github Repository as Composer Dependency
Mock in PHPunit - Multiple Configuration of the Same Method with Different Arguments
Curl Error 60: Ssl Certificate in Laravel 5.4
Codeigniter Check for User Session in Every Controller
Whats the Easiest Way to Determine If a User Is Online? (Php/Mysql)