Connecting a database to Laravel
By Flavio Copes
Learn how to connect a database to Laravel the easy way with SQLite, by setting DB_CONNECTION=sqlite in your .env so a file is created on first migration.
We’re using Laravel in a very basic form, without any database.
Now I want to set up a database and configure Laravel to use it.
After we’ve configured the database, I’ll show you how to use forms to accept user input and store data in the database, and how to visualize this data.
I’ll also show you how you can use data from the database with dynamic routes.
Why start with SQLite?
The easiest way to use a database is by using SQLite.
SQLite stores the entire database in a single file inside your project. There’s no database server to install, no user to create, no password to remember, no port to configure.
That makes it perfect while you’re learning Laravel or prototyping an app. You can always switch to MySQL or PostgreSQL later, and your migrations and Eloquent code stay the same.
Connect the database to Laravel
Laravel reads the database configuration from the .env file. The values there feed into config/database.php.
Open .env, and instead of the default configuration
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=
add
DB_CONNECTION=sqlite
Delete the other DB_ lines. SQLite doesn’t need a host, a port, or credentials.
When DB_DATABASE is not set, Laravel uses the default location for the SQLite file, which is database/database.sqlite.
Create the database
Laravel will automatically create the SQLite database in database/database.sqlite the first time you run a migration:
php artisan migrate
This creates the file and runs the default migrations Laravel ships with, like the users table. You’ll see each migration listed in the output as it runs.
You can also create the file manually before migrating:
touch database/database.sqlite
A common error
Be careful with the DB_DATABASE value. If you leave the old DB_DATABASE=laravel line in .env while using SQLite, Laravel treats that value as the path to the database file.
Since a file called laravel doesn’t exist, you’ll get an error like this:
Database file at path [laravel] does not exist.
The fix is to remove the DB_DATABASE line entirely, or set it to the full path of the .sqlite file.
What about production?
SQLite works fine in production for many small apps, but if you need MySQL or PostgreSQL you only change the .env values back and run your migrations again. Nothing in your application code changes.
Related posts about laravel: