PHP code example of engency / eloquent-formatting

1. Go to this page and download the library: Download engency/eloquent-formatting 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/ */

    

engency / eloquent-formatting example snippets


namespace App\Models;

use Engency\DataStructures\CustomDataFormats;
use Engency\DataStructures\ExportsCustomDataFormats;
use Illuminate\Database\Eloquent\Model;

Class User extends Model implements ExportsCustomDataFormats
{
   use CustomDataFormats;
    
    protected $exports = [
        'default' => [
            'name',
            'age',
            ['posts', ['format' => 'extended']],
            ['created_at', ['dateFormat' => 'yy-m-d']]
        ],
        'limited' => [
            'name'
        ]
    ];

    public function posts() {
        return $this->hasMany(Post::class);    
    }

}

Class Post extends Model implements ExportsCustomDataFormats
{
   use CustomDataFormats;
    
    protected $exports = [
        'default' => [
            'name',
        ],
        'extended' => [
            'name',
            'created_at'
        ]
    ];

}

$user = User::find(1);
$array = $user->toArray(); // exports name, age, posts and created_at
$limited_array = $user->toArray('limited'); // exports only the name-attribute

['posts', ['format' => 'extended']]

['created_at', ['dateFormat' => 'yy-m-d']]