Posts Learn Components Snippets Categories Tags Tools 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

135 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,

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

Load comments for Laravel Retrieve or Create Method

)