Table of contents
In this post, I will explain what is the usage of Laravel Eloquent firstOrNew() and its importance. Laravel provides firstOrNew() will help us to check the record in the database by the given attributes. However, if the model does not found, a new instance will return.
Â
Note: That model returned by firstOrNew has not yet been saved to the database. You will need to manually add save() method to save it.
Â
Â
Example without Laravel firstOrNew()
<?php
namespace App\Http\Controllers;
use App\Models\Post;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class PostsController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$title = 'Post 41';
$post = Post::where('title', $title)->first();
if (is_null($post)) {
$post = new Post(['title' => $title]);
}
$post->description = 'Description for post 41.';
$post->body = 'Body for post 41.';
$post->save();
print_r($post); die;
}
}
Â
Â
Example with Laravel firstOrNew()
<?php
namespace App\Http\Controllers;
use App\Models\Post;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class PostsController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$post = Post::firstOrNew([
'title' => 'Post 41'
]);
$post->description = 'Description for post 44.';
$post->body = 'Body for post 41.';
$post->save();
print_r($post);die;
}
}
Â
As you can see between the two examples above using Laravel firstOrNew() method we don't need additional checking if the returned instance is nulled.
Â
I hope it helps. Thank you for reading :)
Read next