Laravel Checking If a Record Exists

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:

  1. From Laravel 5.6 to 7.x
  2. 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



Leave a reply



Submit