laravel-mongodb icon indicating copy to clipboard operation
laravel-mongodb copied to clipboard

Unable to cast to native type on unknown schema migration

Open sts-ryan-holton opened this issue 2 years ago • 0 comments

  • Laravel-mongodb Version: 3.9.0
  • PHP Version: 8.0.2
  • Database Driver & Version: MongoDB community version 5.0

Description:

I've chosen Mongo DB as a database for my Laravel project for the primary reason of it supporting schema-less data, which is what my project is using.

I'm saving data in my project from another system and have hundreds of fields, so using Mongo DB is perfect for this.

For this reason, I cannot create a migration as such with every possible field with their types as I do not know them, so, my migration simply contains the Laravel specifics with the id, and timestamps, maybe I'll add a few more:

My migration is called: 2022_05_25_133123_create_applications_table.php

/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::create('applications', function (Blueprint $collection) {
        $collection->id();
        $collection->timestamps();
    });
}

My model, is called Application, and it's here where I'm trying to cast a field that's been saved:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Jenssegers\Mongodb\Eloquent\Model;

class Application extends Model
{
    use HasFactory;

    /**
    * The collection associated with the model.
    *
    * @var string
    */
    protected $collection = 'applications';

    /**
     * The attributes that aren't mass assignable.
     *
     * @var array
     */
    protected $guarded = [
        'id',
        'created_at',
        'updated_at'
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array
     */
    protected $casts = [
        'processing_duration_secs' => 'integer'
    ];

    /*
    ** Linked application payday
    */
    public function payday()
    {
        return $this->hasOne(ApplicationPayday::class);
    }

    /*
    ** Linked application response
    */
    public function response()
    {
        return $this->hasOne(ApplicationResponse::class);
    }

    /*
    ** Linked application api links
    */
    public function apiLinks()
    {
        return $this->hasMany(ApplicationApiLink::class);
    }
}

Data is saved like:

Application::create($this->source['Application']);

But my casting when, for instance, looking through tinker, I see that it's still a string?

Steps to reproduce

  1. Set up basic migration without any specific fields
  2. Use Model::create(['processing_duration_secs'=>'5']) to save a field as a string
  3. Add the cast for the field to an integer
  4. Open tinker, query the first model and observe that it's not an integer

Expected behaviour

I should be able to cast fields

Actual behaviour

Casting is not running on fields, what's the solution?

sts-ryan-holton avatar May 26 '22 09:05 sts-ryan-holton