Posts Learn Components Snippets Categories Tags Tools new About
/

Laravel firstOrCreate Code Example

Let's get started with Laravel firstOrCreate method code example

Created on Oct 29, 2021

20 views

In this short snippet, you will learn how to make use of the "firstOrCreate" method in Laravel to retrieve an existing model and if it doesn't exist then it will create a new record. For the example let's find the post with a slug called "hello-world" and if it doesn't exists, then create a new model that has the word "hello-world" as a slug and "Hello World" for the title.
<?php

use App\Models\Post;

$post = Post::firstOrCreate(
    ['slug' => 'hello-world],
    ['slug' => 'hello-world', 'title' => 'Hello World']
);

// No need to call $post->save() method
The "firstOrCreate" method accepts 2 parameters which the 1st one is the attribute to search the model and the 2nd one is the attributes that will be used to create the model.

Other Reads

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️

)