The first() method in Laravel is used to match and find specific data from the database.

It can return only one record at a time. On the other hand, we use the create() method to create new data in Laravel. But using the firstOrCreate() method we can do both tasks at a time.

In this tutorial, you are going to learn how to use the firstOrCreate() method in Laravel with examples.

Suppose, we have a database table named students in our database and there are already some stored data like the full name of students. Here is our database table-

Database table:

Now, the question is what exactly firstOrCreate() works. Right? Well, the answer is it works like a condition.

The firstOrCreate() checks for all the arguments to existing before it finds a match. If not all arguments match, then a new instance of the model will be created.

Let’s try the firstOrCreate() method with existing data-

In controller:

public function view(){
    $student = Student::firstOrCreate([
        'full_name' => 'Deven'
    ]);
    dd($student);
}

In this, example you can see, we called the Student model and apply the firstOrCreate() method. As a parameter, we have to pass an array. In our case, it is ‘full_name’. So, if we print the result with the dd() method, we can see.

output:

Now there is already a student called “Deven” at our table. So, we got the information about “Deven”.

What if we pass data that do not exist in our database. What do you think? Let’s try-

In controller:

public function view(){
    $student = Student::firstOrCreate([
        'full_name' => 'Amit'
    ]);
    dd($student);
}

Now, we have passed data of a new student called “Amit” that is unavailable in our table. The result is-

output:

You can see, there is a new data created in our table whose name is “Amit” and id is 5. If we check our database table we can also see the same result-

Output (Database table):

Note: It does not modify the data. If you only want to check specific data, then use the firstOrCreate()method with only one item in the array.

This will return the first item that matches, or create a new one if no matches are found. Thank you.