How To Set Up A Database In Laravel (Step-by-Step Guide)

How to Set Up a Database in Laravel (Step-by-Step Guide)
Avinash Kumar Aug 10, 2025 112
Laravel,How To Configure Database,MySQL,Database Connection

How to Set Up a Database in Laravel (Step-by-Step Guide)


Introduction

After installing Laravel successfully, the next important step is to configure your database connection. Laravel supports multiple databases such as MySQL, PostgreSQL, SQLite, and SQL Server. In this guide, we’ll focus on setting up a MySQL database in Laravel and running your first migration.

Step 1: Create a Database in MySQL

First, you need a database where Laravel will store all your application’s tables and data.

# Login to MySQL
mysql -u root -p

# Create a new database
CREATE DATABASE laravel_app;

# Exit MySQL
exit;

Replace laravel_app with your preferred database name.

Step 2: Update Laravel's .env File

Laravel stores environment variables, including database credentials, inside the .env file located in the project root directory.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_app
DB_USERNAME=root
DB_PASSWORD=your_password

Make sure the database name, username, and password match your MySQL setup.

Step 3: Update config/database.php (Optional)

By default, Laravel uses the values from .env, but you can manually edit config/database.php if needed. For most projects, editing the .env file is enough.

Step 4: Run Database Migrations

Laravel migrations help you create and manage database tables using PHP code instead of writing raw SQL queries. To run the default migrations:

php artisan migrate

If everything is configured correctly, Laravel will create tables like users, password_resets, and failed_jobs in your database.

Step 5: Test the Database Connection

You can check if Laravel is connected to your database by running a tinker command:

php artisan tinker

// Inside tinker, run:
DB::connection()->getPdo();

If no error is shown, the database connection is working fine.

Common Issues and Fixes

  • Access Denied Error – Check your username and password in the .env file.
  • Port Issues – Make sure MySQL is running on port 3306 or update it accordingly.
  • Cache Issue – After editing .env, run php artisan config:cache to refresh settings.

Conclusion

That’s it! You’ve successfully set up a database in Laravel. Now you can start creating models, migrations, and seeders to manage your application’s data.

WhatsApp Us