How to set default attribute values for Laravel models

### The problem: 

Given the following schema:

```php
 Schema::create('posts', function (Blueprint $table) {
      $table->id();
      $table->unsignedBigInteger('number_of_hits')->default(0);
      $table->string('title');
  });
```

We when we create a new post:

```php
$post = new Post(["title" => "test"]);
```
we might expect the 'number_of_hits' to be 0, but it is null. 

### The solution:

To fix this, we can easily tell Laravel what default values we want for the model attributes:

```php
class Post extends Model
{
   ...
   protected $attributes = [
        'number_of_hits' => 0,
    ];
}
```

Denisa Halmaghi
07 Dec 2021
« Back to post