Laravel Eloquent has quite a few "two-in-one" features: do something or do something else. And I will demonstrate a few of them now.
Example 1: firstOrCreate()
What if you want to get the first record by some condition and create that record if it doesn't exist?
So, this is a typical code. You do where()
and then first()
. If it doesn't return anything, then you create the record.
use App\Models\User; class HomeController extends Controller{ public function index() { $user = User::where('email', 'admin@admin.com')->first(); if (! $user) { User::create([ 'name' => 'Admin', 'email' => 'admin@admin.com', 'password' => bcrypt('password'), ]); } return $user->id; }}
Laravel allows you to do that in one sentence without the if-statement, with firstOrCreate()
.
use App\Models\User; class HomeController extends Controller{ public function index() { $user = User::firstOrCreate( ['email' => 'admin@admin.com'], ['name' => 'Admin', 'password' => bcrypt('password')] ); return $user->id; }}
There are two parameters here. So first, by which condition should you specify more fields. The second parameter is other fields for creating a record.
Example 2: firstOrNew()
Similar to the first example, but here the record...