Originally posted @ https://codeanddeploy.com visit and download the sample code: https://codeanddeploy.com/blog/laravel/laravel-8-eloquent-firstornew-example
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 this tutorial can help you. Kindly visit here https://codeanddeploy.com/blog/laravel/laravel-8-eloquent-firstornew-example if you want to download this code.
Happy coding :)
Top comments (0)