Reputation: 2449
Eloquent has a firstOrCreate
method which gets a model based on a condition, or creates it if it doesn't exist.
Is there any equivalent method in Laravel's query builder (i.e. NOT in Eloquent)? For example:
$row = DB::table('users')->where('user_id', 5)->firstOrCreate('name' => 'Peter', 'last_name' => 'Pan');
That would try to get a row from users
with 'user_id'==5
. If it doesn't exist, it would insert a row with that id number, plus the other mentioned fields.
EDIT: I'm not trying to apply my question with users. I used users as an example to make as clear as possible what I'm looking for.
Upvotes: 0
Views: 3533
Reputation: 650
updateOrInsert
function with empty values give me the result like firstOrCreate
Upvotes: 3
Reputation: 11
Nope, Laravel firstOrCreate is function, that says next:
public function firstOrCreate(array $attributes, array $values = [])
{
if (! is_null($instance = $this->where($attributes)->first())) {
return $instance;
}
return tap($this->newModelInstance($attributes + $values), function ($instance) {
$instance->save();
});
}
But you can add it with query micro:
DB::query()->macro('firstOrCreate', function (array $attributes, array $values = [])
{
if ($record = $this->first()) {
// return model instance
}
// create model instance
});
So than you will be able to call it same way you do with Eloquent.
$record= DB::table('records')->where('alias', $alias)->firstOrFail();
Upvotes: 1
Reputation: 169
Yeah of course! Just use normal SQL and ->selectRaw( your conditions )
and look for if there is a entry where your specifications are.
https://laravel.com/docs/5.7/queries#raw-expressions
Upvotes: -3