Read and Write Database Connections in Laravel

Hafiq Iqmal
3 min readApr 1, 2021

Separating database into read and write connections is recommended when you can every heavy-read application. Thus, it will reduce the pressure connection flood to database when having single database.

Why recommended R/W database ? This architecture serves the purpose of safeguarding site reliability. If a site receives a lot of traffic and only single database available, it will be overloaded with reading and writing requests and leads the entire system tend to slowing down.

In I will show you 2 way you can do to configure read/write connection in Laravel.

But, please remind that, you will be facing replication lag where sync between read and write might be differ in millisecond depending on network speed and bandwidth.

Method 1 : Create new connections in database.php

This is the hard way which i used before when i too lazy to read Laravel documentation 😂.

All you need to do is duplicate the mysql connection.

'mysql' => [
....
],
'mysql_readonly' => [
....
],

--

--

Hafiq Iqmal
Hafiq Iqmal

Written by Hafiq Iqmal

Technical Lead | Software Engineer | Laravel Enthusiasts | Tech writer | UiTM Alumni | Husband | Proud father of a beautiful daughter

No responses yet