Leff
Leff

Reputation: 1340

Laravel - firstOrCreate not persisting all fields to the DB

I am using the firsOrCreate method to persist records if they already don't exists in the DB. This is my function:

  return ContentType::firstOrCreate(
    ['name' => $type], ['slug' => str_slug($type, '-')]
  );

The problem I have here is that the new record is created in the DB, but the slug field stays empty. Not sure why is that since the slug is created, because when I do

dd(str_slug($type, '-'));

Before the method firstOrCreate() I do get the slug. So, why it is not persisted to the DB?

I have set up in my model the protect guarded array so, that should not be the problem:

    protected $guarded = [
        'id'
    ];

Upvotes: 0

Views: 1709

Answers (3)

Hasan Tareque
Hasan Tareque

Reputation: 1741

first setup $fillable in your model as follows:

/**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
        'slug',
    ]; 

Then try the following way to insert

 $data = array(
    'name' => $type,
    'slug' => str_slug($type, '-')
    ); 

 return ContentType::firstOrCreate($data);

Upvotes: 0

Steve Bauman
Steve Bauman

Reputation: 8688

Is your slug field in your $fillable attributes array in your model? Otherwise it won't be inserted due to it being protected:

use Illuminate\Database\Eloquent\Model;

class ContentType extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
        'slug',
    ];
}

For anyone else looking, Laravel 5.3/5.4 supports this second array:

https://github.com/laravel/framework/blob/5.4/src/Illuminate/Database/Eloquent/Builder.php#L349-L365

https://github.com/laravel/framework/blob/5.3/src/Illuminate/Database/Eloquent/Builder.php#L251-L271

However Laravel 5.2 and below does not:

https://github.com/laravel/framework/blob/5.2/src/Illuminate/Database/Eloquent/Builder.php#L243-L260

Upvotes: 1

LMS94
LMS94

Reputation: 1036

You will need to ensure that the slug and name properties are fillable.

If your ContentType model, ensure the fillable property looked like:

class ContentType 
{
    protected $fillable = ['name', 'slug'];
}

Upvotes: 2

Related Questions