<?php use App\Models\Post; $post = Post::firstOrCreate( ['slug' => 'hello-world], ['slug' => 'hello-world', 'title' => 'Hello World'] ); // No need to call $post->save() method

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.
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.
Topics:
Frontend
Resource
Average
Average
Support Us
If you like our tutorial, support us by being our Patreon or buy us some coffee ☕️
Leave a reply