DatabaseCustomCastsTest.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <?php
  2. namespace Illuminate\Tests\Integration\Database;
  3. use Illuminate\Database\Eloquent\Casts\AsArrayObject;
  4. use Illuminate\Database\Eloquent\Casts\AsCollection;
  5. use Illuminate\Database\Eloquent\Casts\AsStringable;
  6. use Illuminate\Database\Eloquent\Model;
  7. use Illuminate\Database\Schema\Blueprint;
  8. use Illuminate\Support\Facades\Schema;
  9. use Illuminate\Support\Str;
  10. class DatabaseCustomCastsTest extends DatabaseTestCase
  11. {
  12. protected function defineDatabaseMigrationsAfterDatabaseRefreshed()
  13. {
  14. Schema::create('test_eloquent_model_with_custom_casts', function (Blueprint $table) {
  15. $table->increments('id');
  16. $table->text('array_object');
  17. $table->text('collection');
  18. $table->string('stringable');
  19. $table->timestamps();
  20. });
  21. }
  22. public function test_custom_casting()
  23. {
  24. $model = new TestEloquentModelWithCustomCasts;
  25. $model->array_object = ['name' => 'Taylor'];
  26. $model->collection = collect(['name' => 'Taylor']);
  27. $model->stringable = Str::of('Taylor');
  28. $model->save();
  29. $model = $model->fresh();
  30. $this->assertEquals(['name' => 'Taylor'], $model->array_object->toArray());
  31. $this->assertEquals(['name' => 'Taylor'], $model->collection->toArray());
  32. $this->assertEquals('Taylor', (string) $model->stringable);
  33. $model->array_object['age'] = 34;
  34. $model->array_object['meta']['title'] = 'Developer';
  35. $model->save();
  36. $model = $model->fresh();
  37. $this->assertEquals([
  38. 'name' => 'Taylor',
  39. 'age' => 34,
  40. 'meta' => ['title' => 'Developer'],
  41. ], $model->array_object->toArray());
  42. }
  43. }
  44. class TestEloquentModelWithCustomCasts extends Model
  45. {
  46. /**
  47. * The attributes that aren't mass assignable.
  48. *
  49. * @var string[]
  50. */
  51. protected $guarded = [];
  52. /**
  53. * The attributes that should be cast to native types.
  54. *
  55. * @var array
  56. */
  57. protected $casts = [
  58. 'array_object' => AsArrayObject::class,
  59. 'collection' => AsCollection::class,
  60. 'stringable' => AsStringable::class,
  61. ];
  62. }