C
C
Camaro672018-05-24 14:26:18
Laravel
Camaro67, 2018-05-24 14:26:18

Is it possible to execute firstOrCreate without setting $fillable on the model itself?

Hello!
The crux of the issue is in the title. For example, instead of Model::create(...) , you can do Model::forceCreate(...) . And something similar for firstOrCreate can be done i.e. without specifying $fillable or $guarded on the model itself? Tried something like this Model::newModelInstance()->fillable(['field'])->firstOrCreate(...) but that naturally doesn't work.
This option is also not very like it. disables completely permissions for bulk filling, until you turn it back on.

Model::unguard();
Model::firstOrCreate(...);
Model::reguard();

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Mashletov, 2018-05-24
@Camaro67

$model = Model::first() ?? Model::forceCreate(...);

I
iljaGolubev, 2018-05-24
@iljaGolubev

That won't work.
But you can override the method in my model

public function firstOrNew(array $attributes, array $values = [])
    {
        if (! is_null($instance = $this->where($attributes)->first())) {
            return $instance;
        }
        // return $this->newModelInstance($attributes + $values);
       // create new logic
       DB::insert('insert into table (id) values (?)', [100500]);
       return $this->find(100500)
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question