Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

FabianH's avatar

Year and Month as Date Field in database?

Im working in a project where a requirement is that the date gets passed in the 'Y-m' format - for example '2009-10'.

I created a model "Unit", with

  protected $dateFormat = 'Y-m';

    protected $table = 'units';
    protected $fillable = ['parent_id', 'longname', 'name', 'from_date', 'to_date'];
    protected $dates = ['from_date', 'to_date'];

the migration looks like the following

 Schema::create('units', function (Blueprint $table) {
             $table->engine = 'InnoDB';
            $table->increments('id' );
            $table->unsignedInteger('parent_id')->nullable();
             $table->foreign('parent_id')->references('id')->on('units');
            $table->string('name');
            $table->string('longname');
            $table->dateTime('from_date');
            $table->dateTime('to_date');
            $table->timestamps();
        });

So the data should get converted from the user input "2009-10" to a date or datetime field in the database, but currently if i do

Unit::create(['parent_id' => null,'longname' => $faker->sentence(3) , 'from_date' => '2009-11', 'to_date' => '2015-11',  'name' => strtoupper(substr($faker->word, 1, 3))]);

the entry in the database is just "0000-00-00 00:00:00"

and i get a

ErrorException in Carbon.php line 414:
Trailing data

is there a way to insert Year Month from user input?

I tried accessors and mutators, but to no avail

0 likes
2 replies
mstnorris's avatar
Level 55

Use Carbon::createFromFormat('Y-m', $dateVariable);

FabianH's avatar

yeah, the problem was protected $dateFormat = 'Y-m'; and some minor bugs in the rest of my code. thank you

Please or to participate in this conversation.