9 Steps to Connect Database to Laravel
The database is an important element in any application. Let’s look in to the 9 Steps to Connect a Database to Larvel by the №1 Mobile App Development Company in Chennai. In general Laravel by default provides the support of MySQL. Where as the MySQL is a well-known, open-source RDBMS (Relational Database Management System).
Here are the 9 steps to connect your (MySql) Database to Laravel:
Process for Connecting to the Database:
- Step 1: First we have to create a database. So, we will start Apache and MySQL servers from XAMPP Control Panel.
- Step 2: Open any web browser, like Chrome, and type localhost/phpmyadmin in URL.
- Step 3: Now, click on the Databases tab and there, write the database named as sample and click on create.
- Step 4: Now, you will have to find a file named .env, where you will have to specify the details for the MySQL server, like database name, username, etc. In that file, you will have to search for names starting with DB_.
- Step 5: In that, you will find the DB_CONNECTION=mysql line. Below this are all the details specified for the database connection. You will have to specify the database name sample, that we created, after DB_DATABASE= and also specify username and password according to your need. Then save the file.
- Step 6: Now, we will create a View in resources/views directory with the name demo.blade.php. Write the below code in the file.
<!DOCTYPE html>
<html>
<head>
<title>Demo Sample</title>
<style>
div {
font-size: 22px;
}
</style>
</head>
<body>
<div>
<?php
if(DB::connection()->getPdo())
{
echo “Successfully connected to the database => “
.DB::connection()->getDatabaseName();
}
?>
</div>
</body>
</html>
Step 7: Write the following route in the ‘web.php’ file in ‘routes’ directory.
Route::get(‘blade’, function () {
return view(‘demo’);
});
Step 8: Now, run the following Laravel artisan command to start the server:
php artisan serve
Step 9: And now, open the provided URL by the artisan in the browser with /blade at the end.
http://127.0.0.1:8000/blade
Conclusion:
Connecting to databases and running queries is a breeze with Laravel.
app/config/database.php is the database configuration file.
Well, you can define all of your database connections in this file, as well as which one should be utilised by default. Hope you like the 9 using the Steps to Connect a Database to Laravel.
For more details contact Lia Infaraservices.