Quick way to save or update post with one liner of eloquent code

Typically, we fetch the post with a single or set of criteria to see if it already exists, and if not, we move on to saving or updating. The snippet for saving is below.

$post = Post::where('title', request('title'))->get();
if(!$post) {
$post = Post::create([
		'title' => request('title'),
		'post_text' => request('description'),
	]);
} 

However, above code can be replaced in a new way by substituting with one liner of eloquent method using either firstOrCreate() or updateOrCreate(). Their snippets are given below one by one.

// firstOrCreate takes two parameters 
// 1. set of fields to be matched and 
// 2. additional set of fields for saving if given title is not matched with database
$post = Post::firstOrCreate( ['title'=> 'title field to be matched', 'user_id' => 'user_id value to be matched'], ['post_text'=>'first or create save', 'user_id' => 'user_id value to be saved'] );

One thing to keep in mind is that this function will not continue to create if the set of fields specified in the first parameter matches.

// updateOrCreate takes two parameters 
//1. set of fields to be matched and 
//2. additional set of fields for updating if given title is matched with database
$post = Post::updateOrCreate( ['title'=> 'title field to be matched', 'user_id' => 'user_id value to be matched'], ['post_text'=>'update or create update', 'user_id' => 'user_id value to be updated'] );

One thing to keep in mind is that this function will not update if the set of fields specified in the first parameter does not match.

Related Posts


Using WhereIn

Updating multiple rows

Using Like

Using orWhere

What is Query Builder?

Using "with" in eloquent query

Getting last inserted id

Selecting last row of a table

Using parameters in find() method

Using local scope in eloquent

Using global scope in eloquent