Laravel eloquent firstOrCreate example
Today we will learn about Laravel’s eloquent firstOrCreate example. we will learn the Laravel model firstorcreate eloquent. we can learn easily to use eloquent firstorcreate examples in Laravel.
firstOrCreate() eloquent method to find the record in a database table and returns, if there are no records in the database table then it will create a new record and return. we will show you simple examples, without firstOrCreate() and with firstOrCreate() example.
Without firstOrCreate()
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
use Session;
use Hash;
class RegisterController extends Controller {
public function store(Request $request) {
$this->validate($request,[
'username' => 'required|unique:users',
'email' => 'required|unique:users',
'password' => 'required'
]);
$username = 'joi';
$user = User::where('name', $username)->first();
if (is_null($user)) {
$user = new User(
['name' => $username]
);
}
$user->email = 'devnote@gmail.com';
$user->password = Hash::make('12345678');
$save_id = $user->save();
if($save_id) {
session()->flash('success', 'User successfully created!');
return redirect()->route(users.index);
} else {
session()->flash('error', 'Something went wrong!');
return redirect()->route('users.create');
}
}
}
Also read: Laravel Eloquent updateOrCreate Query Example
With firstOrCreate()
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Http\Request;
class RegisterController extends Controller {
public function store(Request $request) {
$this->validate($request,[
'username' => 'required|unique:users',
'email' => 'required|unique:users',
'password' => 'required'
]);
$save_id = User::firstOrCreate(
[ 'name' => 'joi' ],
[ 'email' => 'devnote@gmail.com', 'password' => Hash::make('12345678') ]
);
if($save_id) {
session()->flash('success', 'User successfully created!');
return redirect()->route(users.index);
} else {
session()->flash('error', 'Something went wrong!');
return redirect()->route('users.create');
}
}
}