Warm tip: This article is reproduced from serverfault.com, please click

Use Model's Casts Array to Verify a Model Integrity on PHPUnit

发布于 2020-12-03 20:05:39

Ambient: PhpStorm, using Laravel and PHPUnit.

What I want: To use the $casts on my users model and do a foreach function to compare all his fields on a specific user, asserting if all variables from database are of the same type of my users model $casts.

Is there any integrated function that already do this for me? If not, please tell me how to make it from scratch.

Thanks.

Questioner
Mateus Bermudes Magalhães
Viewed
0
Donkarnash 2020-12-04 05:35:33

To get the $casts on any model

$user = User::firstOrFail();

$user->getCasts();


/*
 * Output might be an array like

    [
      "id" => "int",
      "email_verified_at" => "datetime",
    ]
*/

However if you declare the casts property on a Model class, Laravel will ensure attribute casting properly - rest assure the functionality to cast attributes as per the $casts array must have been tested thoroughly at framework level.