How to connect to MySQL database in Laravel

Updated: January 16, 2024 By: Guest Contributor Post a comment

Introduction

When working with Laravel, a robust PHP framework, a common task is connecting to a MySQL database to handle data persistence. Laravel makes this process straightforward with its built-in ORM, Eloquent, and database utilities. This tutorial will guide you through the steps of setting up a MySQL connection in a Laravel application, with a focus on practical examples and best practices.

Prerequisites

  • Laravel installation
  • MySQL database server
  • Basic understanding of PHP and Laravel

Basic Configuration

Start by configuring your .env file at the root of your Laravel project with your MySQL database information:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database
DB_USERNAME=your_username
DB_PASSWORD=your_password

With the environment variables is set, check your config/database.php to ensure Laravel uses these variables for database connections:

'mysql' => [
    'driver' => 'mysql',
    'url' => env('DATABASE_URL'),
    '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', ''),
    // ...Additional configuration
],

Creating a Model and Migration

To interact with the database, you’ll need a corresponding Eloquent model. Let’s create a model for a table named products:

php artisan make:model Product -m

This command generates a model and a database migration file where you can define the table schema:

public function up()
{
    Schema::create('products', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->decimal('price', 8, 2);
        $table->timestamps();
    });
}

Run the migration with the command below to create the table in your MySQL database:

php artisan migrate

Interacting with the Database

To add a new product, first ensure your Product model has the fillable or guarded attributes set, and then use Eloquent to insert data:

use App\Models\Product;

$product = new Product;
$product->name = 'Amazing Widget';
$product->price = 99.99;
$product->save();

To retrieve data, use the following:

$products = Product::all();

The $products variable will hold a Collection of Product models returned from the database.

Advanced Usage

You can also use the Laravel Query Builder for more complex queries:

$expensiveProducts = DB::table('products')
    ->where('price', '>', 100)
    ->get();

This will retrieve products with a price greater than 100. Don’t forget to import the DB facade at the top of your PHP file:

use Illuminate\Support\Facades\DB;

Conclusion

In conclusion, connecting to a MySQL database in Laravel is a simple and efficient process. By correctly setting your configuration files and utilizing Laravel’s Eloquent and Query Builder, you can easily interact with your data.