1. Go to this page and download the library: Download dimalebid/laravel-json-cast library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
dimalebid / laravel-json-cast example snippets
namespace App\Models\User;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use App\Models\User\Settings\Settings;
class UserSettings implements CastsAttributes
{
public function get($model, string $key, $value, array $attributes)
{
return new Settings((array)json_decode($value, true));
}
public function set($model, string $key, $value, array $attributes)
{
return json_encode(get_object_vars($value));
}
}
namespace App\Models\User\Settings;
use DimaLebid\LaravelJsonCast\JsonCastable;
use App\Models\User\Settings\Auth;
class Settings extends JsonCastable
{
public Auth $auth;
public string $country = 'Ukraine';
public ?string $phone;
public function __construct(array $attributes)
{
$this->auth = new Auth($attributes);
parent::__construct($attributes);
}
}
namespace App\Models;
use App\Values\Address;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
protected $casts = [
'settings' => UserSettings::class,
];
}