Home / Snippets / Laravel Retrieve or Create Method
Laravel Retrieve or Create Method cover

Laravel Retrieve or Create Method

147

3 years ago

0 comments

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