flyingL123
flyingL123

Reputation: 8046

Laravel Eloquent ORM firstOrNew mass assignment exception

I'm trying to look up a model in my database based on 2 fields, and if it doesn't exist, create a new model which contains those two values. I'm attempting to use the firstOrNew method to achieve this:

$store = Store::firstOrNew(array('ext_hash' => $ext_hash, 'ext_type_id' => EXT_TYPE_ID));

However, this code is throwing a MassAssignmentException.

Is the only way to avoid this exception to assign fillable properties on the class level? According to the documentation, I should be able to assign fillable properties on the instance level, rather than for the entire class, but how would I do that?

Here's the code for the Store model:

<?php

use Illuminate\Database\Eloquent\SoftDeletingTrait;

class Store extends Eloquent{

        use SoftDeletingTrait;

        public function products(){
                return $this->hasMany('Product');
        }

        public function faqs(){
                return $this->hasMany('ProductFaq');
        }

        public function customer_questions(){
                return $this->hasMany('CustomerQuestion');
        }

        public function users(){
                return $this->hasMany('User');
        }

}

Upvotes: 3

Views: 2054

Answers (1)

Jarek Tkaczyk
Jarek Tkaczyk

Reputation: 81147

fillable() is the method you need:

$search = array('ext_hash' => $ext_hash, 'ext_type_id' => EXT_TYPE_ID);

$store = (Store::where($search)->first())
  ?: with(new Store)->fillable(array_keys($search))->fill($search);

or:

$store = new Store;

$store = ($store->where($search)->first()) ?: $store->fillable(array_keys($search))->fill($search);

Upvotes: 3

Related Questions