jlrdw's avatar
Level 75

Database connection

When you do a query, is a connection established at that time and disposed of after results are done, or is connection always alive? Something like

 public function index()
    {
        $users = DB::table('users')->get();

        return view('user.index', ['users' => $users]);
    }
0 likes
6 replies
ejdelmonico's avatar

It looks like the framework uses a UNIX socket or a Host/Port connection when looking at illuminate\Database\Connectors\MySqlConnector. I don't see any kind of timeout or keep alive. All I could find was many checks to see if connection alive. So, I am assuming that the connection is kept alive.

1 like
Gog0's avatar
Gog0
Best Answer
Level 2

As far as I know PHP closes connections at the end of the script if not specificaly asked to be persistent connections, and I believe Laravel don't do that, then I'd say yes, the connection is closed.

1 like
jlrdw's avatar
Level 75

@ejdelmonico dug and found this note in that file

public function connect(array $config)
    {
        $dsn = $this->getDsn($config);

        $options = $this->getOptions($config);

        // We need to grab the PDO options that should be used while making the brand
        // new connection instance. The PDO options control various aspects of the
        // connection's behavior, and some might be specified by the developers.

/////////more code

I was wondering if you are paginating a resultset, is a brand new connection established each time. I know in an older style "single page php / pdo" application I am pretty sure the connection instance was created and disposed between each page load.

1 like
ejdelmonico's avatar

@jlrdw That is a great question. You would think that once a connection is made, it would persist for at least a certain amount of time for efficiency. I do think Laravel Paginator is setup to grab all data to be paginated at start and then paginate results as instructed. Have a look here laravel/framework/src/Illuminate/Session/DatabaseSessionHandler.php

1 like
Gog0's avatar

By the way, if you want to manually close your connection you can use the DB Facade method DB::disconnect();

1 like
jlrdw's avatar
Level 75

@Gog0 that answers it, I searched the vendor folder for any occurence of

PDO::ATTR_PERSISTENT

No matches. So I guess Taylor just leaves it to PDO. And Thanks @ejdelmonico for pointing me in the right direction, that file you referenced.

1 like

Please or to participate in this conversation.