Pre-requisites:
XAMPP
Make sure MySQL is installed on your system
Download XAMPP
XAMPP provides a local development environment that includes a MySQL database server
In the XAMPP control panel, locate the "MySQL" module, and click the "Start" button next to it
Next, click on "Admin" next to the "Stop" button to open phpMyAdmin
You can also access PhpMyAdmin by navigating to http://localhost/phpmyadmin in your web browser after starting the XAMPP server.
The default username and password for XAMPP's MySQL database are:
Username: root
Password: null (empty)
Click "New" and input your database name and click the "Create" button
Database credentials are by default stored in .env files
.env is short for environment
Make sure to enter all the valid details in the .env file for the database connection to MySQL
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=example_app DB_USERNAME=root DB_PASSWORD=
Locate the path resources/views and create a new file named testdbconn.blade.php
Add the following code
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Check Database Connection in Laravel</title> </head> <body> <div> <?php if(DB::connection()->getPDO()) { echo "Connected successfully to database and the database name is ".DB::connection()->getDatabaseName(); } ?> </div> </body> </html>
Locate the path /routes/web.php and create a new route
<?php use Illuminate\Support\Facades\Route; Route::get('/', function () { return view('welcome'); }); Route::get('/testdbconn', function() { return view('testdbconn'); });
Navigate to your project directory in terminal, then type
php artisan serve
In the browser, we can see the server running on
http://127.0.0.1:8000
Now, use this route
http://127.0.0.1:8000/testdbconn
If connected successfully, the output should return the following with your database name
Connected successfully to database and the database is example_app