Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon Laravel Checking If a Record Exists
    Laravel check record existence Eloquent methods exists() method first() method firstOrCreate() method


Laravel Checking If a Record Exists


To check if a record exists in Laravel, you can use the `exists()` method provided by Eloquent. Here are a few examples:

php
// Using exists()
if (User::where('email', Input::get('email'))->exists()) {
    // User with the given email exists
}

php
// Using first()
$user = User::where('email', Input::get('email'))->first();
if ($user !== null) {
    // User with the given email exists
}

php
// Using firstOrCreate()
$user = User::firstOrCreate([
    'email' => Input::get('email'),
], [
    'name' => Input::get('name'),
    'password' => bcrypt(Input::get('password')),
]);

if ($user->wasRecentlyCreated) {
    // User was just created
} else {
    // User already existed
}

The `exists()` method directly checks if any records match the given constraints, returning a boolean value[1][3][4].

Alternatively, you can use `first()` to retrieve the first matching record and check if it is not null[1][2].

Another useful method is `firstOrCreate()`, which checks if a record exists based on the given constraints, and if not, creates a new record with the provided attributes[3][5].

To determine if the record was just created, you can check the `wasRecentlyCreated` property of the model instance[5].

Citations:
[1] https://stackoverflow.com/questions/27095090/laravel-checking-if-a-record-exists
[2] https://www.itsolutionstuff.com/post/how-to-check-if-record-exists-or-not-in-laravel-5example.html
[3] https://devdojo.com/bobbyiliev/how-to-check-if-a-record-exists-with-laravel-eloquent
[4] https://www.educative.io/answers/how-to-determine-if-a-record-exists-in-the-database-in-laravel
[5] https://www.youtube.com/watch?v=w7x76bpp0QE