Laravel5.7 : MySQL Setup and Initial Migration. [Solved] “Illuminate\Database\QueryException : could not find driver (MySQL)”

We will connect our database in the framework and start performing CRUD operation. Before that, we need to do the necessary setup in laravel’s config files.  Today’s blog is a step by step guide to do the database config and make a successful database migration. After the database is set we will work in the CRUD Operations.

Database Configurations in .env file

In your application’s .env file you need to add the information of connection, host, port, database, username, and password. To edit the file with your configuration values.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=dbname
DB_USERNAME=root
DB_PASSWORD=secret

After saving the changes we are ready to make the migration. So in your terminal type:

php artisan migrate

With these minor changes you should have following tables migrated in your MySQL server:

| migrations |
| password_resets |
| users |

Illuminate\Database\QueryException: could not find driver (MySQL)

This is a possible error you will encounter during the migration. Before that let’s make sure you have following things set up:

  • Installed MySQL Server?
  • Installed the exact version of MySQL compatible with your PHP?
  • Did you create the database in your SQL Server before doing the migration?

Let’s walk through each of them

Install MySQL-Server in Ubuntu

In your terminal type: Sudo apt install mysql-server

Install MySQL Extension for your PHP

After the installation of MySQL Server in your terminal type:

sudo apt-get install php7.1-mysql

Your PHP version might be different so check your PHP version by typing php -v. Then choose whether it’s php7.1-mysql or php7.2-mysql. After installation of the extension, now you need to create your database from MySQL

From terminal login to your SQL server:

mysql -u root -p
create database dbname;
show databases;

You should now have your database displayed in the console. Now get out of the SQL console and in your terminal type php artisan migrate. Your migration will be successful without any error. To verify if the tables I named above are displayed or not, again login to your sql:

mysql -u root -p
show databases;
use testdatabase;
show tables;

You will find following tables: migrations, password_resets, users. With these we are done with doing the initial setup of mysql database in Laravel framework. Next lesson to learn will be performing CRUD operations.

Related Posts: