Skip to content

Instantly share code, notes, and snippets.

@adduc
Last active January 24, 2025 19:09
Show Gist options
  • Save adduc/48e38c13229ed376c3d44b9f507571b5 to your computer and use it in GitHub Desktop.
Save adduc/48e38c13229ed376c3d44b9f507571b5 to your computer and use it in GitHub Desktop.
Laravel Eloquent PoC: Use existing PDO connection in standalone application
{
"autoload": {
"psr-4": {
"App\\": "src/"
}
},
"require": {
"illuminate/database": "^9.13"
}
}
<?php
declare(strict_types=1);
use App\Models;
use Illuminate\Database\Capsule;
use Illuminate\Database\Connection;
use Illuminate\Database\SQLiteConnection;
$db_file = __DIR__ . '/sqlite.sqlite';
// bootstrap
(function () use ($db_file) {
require __DIR__ . '/vendor/autoload.php';
$capsule = new Capsule\Manager();
$capsule->addConnection([
'driver' => 'pdo',
'database' => '',
'pdo' => fn() => new PDO('sqlite:' . $db_file),
]);
$capsule->setAsGlobal();
$capsule->bootEloquent();
Connection::resolverFor('pdo', function (PDO|Closure $closure, string $database, string $prefix, array $config) {
return new SQLiteConnection($config['pdo'], $database, $prefix, $config);
});
})();
// Migration
(function () use ($db_file) {
if (file_exists($db_file)) {
return;
}
touch($db_file);
Capsule\Manager::schema()->create('users', function ($table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->string('userimage')->nullable();
$table->string('api_key')->nullable()->unique();
$table->rememberToken();
$table->timestamps();
});
Capsule\Manager::schema()->create('todos', function ($table) {
$table->increments('id');
$table->string('todo');
$table->string('description');
$table->string('category');
$table->integer('user_id')->unsigned();
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
})();
(function () {
$user = Models\User::firstOrCreate([
'email' => "[email protected]",
], [
'name' => "Test User",
'password' => password_hash("changeme", PASSWORD_BCRYPT),
]);
if (!$user->todo()->count()) {
$user->todo()->create([
'todo' => "Working with Eloquent Without PHP",
'category' => "eloquent",
'description' => "Testing the work using eloquent without laravel"
]);
}
print_r($user->toArray());
print_r($user->todo->toArray());
})();
<?php
declare(strict_types=1);
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Todo extends Model
{
protected $fillable = ['todo','category','description'];
}
<?php
declare(strict_types=1);
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations;
class User extends Model
{
protected $fillable = [
'name', 'email', 'password', 'userimage'
];
protected $hidden = [
'password', 'remember_token',
];
public function todo(): Relations\HasMany
{
return $this->hasMany(Todo::class);
}
}
@brendandebeasi
Copy link

Thank you for posting this 🙏 I was banging my head trying to integrate PHPDebugBar into a non-Laravel project using Eloquent.

Note that this works with any DB type. Just make sure you pass the full config

        [
            'driver' => 'pdo',
            'host' => $DB_HOST,
            'database' => $DB_DATABASE,
            'username' => $DB_USER,
            'password' => $DB_PASS,
            'charset' => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix' => '',
            'pdo' => $pdoEloquentReader
        ];

and

    Connection::resolverFor('pdo', function (PDO|Closure $closure, string $database, string $prefix, array $config) {
        return new \Illuminate\Database\MySqlConnection($config['pdo'], $database, $prefix, $config);
    });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment