Posts Learn Components Snippets Categories Tags About
/

Laravel Retrieve or Create Method

Learn the 2 different types of method to retireve a model or create it in Laravel

Created on Aug 04, 2021

8 views

There are 2 methods that allow you to retrieve a model if exists otherwise create or update the model instance. These methods are:
  • firstOrCreate()
  • updateOrCreate()

Laravel FirstOrCreate Method
This method allows you to retrieve the first model of the given condition if available, otherwise a new model instance will be created and stored in the database.
<?php

$post = Post::firstOrCreate(['title' => 'post 2']);

// if 'post 1' exists the it will be retrieved
// otherwise 'post 1' doesn't exists, 'post 2' will be created

A more complex condition to retrieve the model will be like below.
<?php

Post::where('slug', 'post-1')
    ->whereNotNull('summary')
    ->firstOrCreate([/* your content here*/]);

Laravel UpdateOrCrate Method
For this method, you can update the existing model or create a new modal.
Post::updateOrCreate(['slug' => 'post-1'], ['slug' => 'post-1', 'summary' => 'hello world']);

The code above will try to update the post with a slug called 'post-1' with the value of the summary. If it doesn't exists then the new post will be created,

Snippets by

PostSrc poster

PostSrc

Full stack developer mainly focusing on the front end side of the web. The main author of PostSrc and loves writing tutorial and guides online.

Load comments for Laravel Retrieve or Create Method

new

PostSrc Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that's right for your project.

View Components

Other Code Snippets

More