How To Connect Database In Laravel With Example

1
418
laravelconnection

Connecting to databases is made easy with Laravel. This guide will take you through the process of connecting to a database in Laravel using MySQL as an example.

To begin, you will need to edit the .env(Location:- root directory of your application will contain a . env ) file and add your database credentials as shown below:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=password

After this, create a connection file in the config/database.php file following this format:

‘mysql’ => [
‘driver’ => ‘mysql’,
‘host’ => env(‘DB_HOST’, ‘127.0.0.1’),
‘port’ => env(‘DB_PORT’, ‘3306’),
‘database’ => env(‘DB_DATABASE’, ‘forge’),
‘username’ => env(‘DB_USERNAME’, ‘forge’),
‘password’ => env(‘DB_PASSWORD’, ”),
],

Once you have completed these steps, run the migrate command to create tables in your database using php artisan migrate.

That’s it! You can now interact with your database within your Laravel application using the DB facade. For instance, you can query the users table like this:

$users = DB::table(‘users’)->get();

1 COMMENT

LEAVE A REPLY

Please enter your comment!
Please enter your name here