Laravel PostgreSQLに接続する
Laravel 5.8からPostgreSQLに接続してみます。接続ライブラリ
PHPからPostgresqlへの接続ライブラリをインストールしておきます。
$ sudo apt install php-pgsql
設定ファイルの編集
ローカルにインストールしたPostgreSQL
データベース:sample
ユーザー名:pgadmin
パスワード:P@ssw0rd
上記のデータベースに接続してみます。
.envファイルの該当箇所を編集。
DB_CONNECTION=pgsql
DB_HOST=127.0.0.1
DB_PORT=5432
DB_DATABASE=sample
DB_USERNAME=pgadmin
DB_PASSWORD=P@ssw0rd
Laravel コンソールから実行するバッチプログラムの作成
こちらで調べたコンソールコマンドで接続を試してみます。
データベースに接続するため、「use Illuminate\Support\Facades\DB」を追加。
サンプルは以下のようになりました。
- <?php
- namespace App\Console\Commands;
- use Illuminate\Console\Command;
- use Illuminate\Support\Facades\DB;
- class SampleCommand extends Command
- {
- protected $signature = 'my:command';
- protected $description = 'コマンドサンプル';
- public function __construct()
- {
- parent::__construct();
- }
- public function handle()
- {
- $rows = DB::select('select * from test');
- var_export($rows);
- }
- }
コマンドを実行してテスト
$ php artisan my:command
これでtestテーブルの中身が検索できました。
ちゃんとデータベースに接続できたようです。