Sling Academy
Home/PHP/How to connect to MySQL database in Laravel

How to connect to MySQL database in Laravel

Last updated: January 16, 2024

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.

Next Article: How to Execute SQL Queries in Laravel

Previous Article: How to implement CI/CD in Laravel: A practical guide

Series: Laravel & Eloquent Tutorials

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array