PHP code example of petrknap / eloquent

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

    

petrknap / eloquent example snippets


namespace PetrKnap\Eloquent\Casts;

use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Carbon;

/**
 * @property Carbon $local_datetime
 * @property Carbon $utc_datetime
 */
final class SomeModel extends Model
{
    protected function casts(): array
    {
        return [
            'utc_datetime' => AsUtc::dateTime(),
            'local_datetime_utc' => AsUtc::dateTime(readonly: true),
            'local_datetime_timezone' => AsPrivate::class,
        ];
    }

    protected function localDatetime(): Attribute
    {
        return AsUtc::withTimezone(
            'local_datetime_utc',
            $this->getDateFormat(),
            'local_datetime_timezone',
        );
    }
}

$datetime = Carbon::parse('2025-12-06 11:58:21 Europe/Prague');

$model = new SomeModel();
$model->utc_datetime = $datetime;
$model->local_datetime = $datetime;
$model->save();

$model->refresh();
printf(
    "  UTC DT: %s %s\nLocal DT: %s %s\n",
    $model->utc_datetime->toDateTimeString(), $model->utc_datetime->getTimezone(),
    $model->local_datetime->toDateTimeString(), $model->local_datetime->getTimezone(),
);

namespace PetrKnap\Eloquent;

// someone selects the model as option
$modelOption = Optional::ofSole(
    Some\Model::query()->where('value', '=', 'unique'),
);

// someone else decides that it must be found and prints it
printf(
    "There is exactly one %s result.\n",
    $modelOption->orElseThrow()->value,
);

namespace PetrKnap\Eloquent;

function some_update(Some\ModelRepository $modelRepository): void
{
    $modelRepository->getConnection()->transaction(function () use ($modelRepository): void
    {
        foreach ($modelRepository->findByValue('common', lockForUpdate: true) as $commonModel)
        {
            $commonModel->value .= ' #' . $commonModel->id;
            $modelRepository->save($commonModel);
        }
    });
}
some_update(new Some\ModelRepository());

use Illuminate\Database\Connection;
use Illuminate\Support\Collection;
use PHPUnit\Framework\TestCase;

class SomeTest extends TestCase
{
    public function testUpdates(): void
    {
        $model = new Some\Model();
        $model->id = 1;
        $model->value = 'common';

        $connection = self::createMock(Connection::class);
        $connection->expects(self::once())->method('transaction')
            ->willReturnCallback(fn (callable $callback): mixed => $callback($connection));

        $repository = self::createMock(Some\ModelRepository::class);
        $repository->expects(self::once())->method('getConnection')
            ->willReturn($connection);
        $repository->expects(self::once())->method('findByValue')
            ->with($model->value, true)
            ->willReturn(new Collection([$model]));
        $repository->expects(self::once())->method('save')
            ->with($model)
            ->willReturnCallback(function (Some\Model $model): Some\Model {
                self::assertSame('common #1', $model->value);
                return $model;
            });

        some_update($repository);
    }
}
(new SomeTest('example'))->testUpdates();

  UTC DT: 2025-12-06 10:58:21 UTC
Local DT: 2025-12-06 11:58:21 Europe/Prague