PHP code example of yonchando / laravel-cast-attributes

1. Go to this page and download the library: Download yonchando/laravel-cast-attributes 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/ */

    

yonchando / laravel-cast-attributes example snippets



class User extends \Illuminate\Database\Eloquent\Model
{
    protected $fillable = ['json'];

    protected $casts = [
        'json' => UserJson::class
    ];
}

class UserJson extends \Yonchando\CastAttributes\CastAttributes
{
    private string $firstName;
    
    protected string $lastName;
    
    public string $gender;
    
    public Image $image;
    
    public  function getFirstName(): string
    {
        return $this->firstName;
    }
    
    public  function setFirstName(string $firstName):void 
    {
        $this->firstName = $firstName;
    }
    
    public function getLastName(){
        return $this->lastName;
    }
}

class Image
{
    use \Yonchando\CastAttributes\Traits\CastProperty;
    
    public string $filename;
    public int $size;
    public string $path;
    
    public function url()
    {
        return Storage::url($this->path);
    }
}

use Illuminate\Http\Request;

class UserController extends Controller
{
    public function show($id)
    {
        $user = User::find($id);
        
        $user->json->getFirstName();
        $user->json->getLastName();
        $user->json->gender;
        
        // access function in image class
        $user->json->image->url();
        
        // to array
        $user->json->toArray();
        $user->json->image->toArray();
        
    }
    
    public function store(Request $request)
    {
        // use class
        $user = new User([
            'json' => UserJson::create($request->all()),
        ]);
        
        // use an array
        $user = User::create([
            'json' => [
                'first_name' => $request->get('first_name'),        
                'last_name' => $request->get('last_name'),
                'gender' => $request->get('gender'),
                'image' => $request->get('image'),
            ]
        ])
    }
}