Racso
Racso

Reputation: 2449

Laravel firstOrCreate without Eloquent

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

Answers (3)

safiqul islam
safiqul islam

Reputation: 650

updateOrInsert function with empty values give me the result like firstOrCreate

Upvotes: 3

Yura Halias
Yura Halias

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

Aiden Kaiser
Aiden Kaiser

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

Related Questions