0

php artisan migrate works, but I can migrate, but when I try to retrieve a record with eloquent, I get the following error The environment is docker.

SQLSTATE[08006] [7] could not connect to server: Connection refused Is the server running on host "127.0.0.1" and accepting TCP/IP connections on port 5433? (SQL: select * from "reservaions")

.env

DB_CONNECTION=pgsql
DB_HOST=127.0.0.1
DB_PORT=5433
DB_DATABASE=root
DB_USERNAME=root
DB_PASSWORD=pass

docker-compose.yml

  # PostgreSQL
  db:
    image: postgres:9.6
    container_name: myapp-db
    environment:
      POSTGRES_DB: root
      POSTGRES_USER: root
      POSTGRES_PASSWORD: pass
    ports:
      - "5433:5432"
    volumes:
      - ./docker/db/:/docker-entrypoint-initdb.d

controller

 public function getReservations()
    {
        $reservations = Reservaion::all();
        return $reservations;
    }

model

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Reservaion extends Model
{
}

The strange thing is that the DB client tools and migrations have been successful. Why does it fail when accessing the DB from the controller via the model? Thanks.

1 Answer 1

2

In docker-compose you can reach services by their names. Than, in your case, DB_HOST=db

Why work?

Because you have Postgres installed on you computer (not docker) and when you migrate from console - your DB host can connect to 127.0.0.1

For future - work with artisan from docker php service: docker-compose exec {PHP_SERVICE} bash

Sign up to request clarification or add additional context in comments.

3 Comments

oh sorry, edited - host is not pgsql, it's db, copy paste is evil :)
Thank you. I solved the problem by writing the container name of docker-db in .env.
Yes, service name OR container name

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.