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

Casting not working with embedded fields

Open archit8430 opened this issue 1 year ago • 2 comments

  • Laravel-mongodb Version: 5.1
  • PHP Version: 8.2
  • Laravel Version 11
  • Database Driver & Version:

Description:

How to apply for casting when there is embedded fields

Steps to reproduce

  1. Prepare Create Query
User::create([
    'reg_date' => (new Carbon())->format('Y-m-d'),
    'input_params' => [
      'start_date' => (new Carbon())->format('Y-m-d')
     ],
]);
  1. User
namespace App\Models\MongoDb\IpayApp;

use App\Casts\ObjectIdCasts;
use MongoDB\Laravel\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class User extends Model
{
    use HasFactory;
    protected $connection = 'ipay_app';
    protected $table = 'user';
    protected $guarded = [];

    protected $casts = [
        'reg_date' => 'datetime',
        'start_date' => 'datetime',
    ];

}
  1. reg date is casting properly, while on start casting not work

Expected behaviour

Both Should Cast Accordingly, i have missing something, let me know

Actual behaviour

reg date is casting properly, while on start casting not work

Edited to add code blocks.

archit8430 avatar Nov 08 '24 09:11 archit8430

start_date is not the correct field path, it would be input_params.start_date. Off the top of my head I'm not sure if this will work, as you're not embedding a model but "only" storing unstructured data.

alcaeus avatar Nov 08 '24 09:11 alcaeus

The value assigned is a string. In fact, only DateTimeInterface objects can be casted into MongoDB\BSON\UTCDateTime.

GromNaN avatar Dec 17 '24 08:12 GromNaN