Home / Snippets / Laravel firstOrCreate Code Example
Laravel firstOrCreate Code Example cover

Laravel firstOrCreate Code Example

161

3 years ago

0 comments

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

notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

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

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this