Laravel – multiple database connection get average from 3 tables

I have 3 databases

db_1 (students table)

id | students
1  | 42

db_2 (students table)
id | students
1  | 31

db_3 (students table)
id | students
1  | 22

In my controller, how can i get the total average of all students by using only one model (Student). and by just overriding the database connection.


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

The most important bit is the setConnection() method called on Model before querying. Remember that using it this way you need all the connections defined in your config/database.php under connections.

class StudentsController extends Controller {
        const DB_COUNT = 3;
        private $students;
        public function __construct(Students $students) {
            $this->students = $students;

        public function index(Request $request) {
            for ($i=0; $i<self::DB_COUNT; $i++) { //or foreach through config('database.connections', [])
               $students[] = $this->students->find(1)->students;
            //what is "totalAVG" ???
            $totalAvg = array_sum($students) / self::DB_COUNT;

Alternatively if we want to stick to particular connection names:
public function index(Request $request) {
                foreach (config('database.connections', []) as $connName => $params)
                   $students[] = $this->students->find(1)->students;
                //what is "totalAVG" ???
                $totalAvg = !empty($students) ? array_sum($students) / count($students) : 0;

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x