Today I Learned

How to set default attribute values for Laravel models

The problem:

Given the following schema:

 Schema::create('posts', function (Blueprint $table) {

We when we create a new post:

$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:

class Post extends Model
   protected $attributes = [
        'number_of_hits' => 0,