Originally published on laravel.learnio.dev — part of the Laravel best practices course. View this lesson on the original site.

In this lesson

Laravel gives you three layers for database work, raw SQL, the query builder, and Eloquent models. Start simple and choose the right layer for the job.

The three ways Laravel talks to your database

  • Raw SQL (DB::select, DB::statement) for very specific queries.
  • Query Builder (DB::table(...)) for fluent SQL-style operations.
  • Eloquent (User::query()) for model-driven app code.

Most applications use Eloquent for everyday CRUD and Query Builder for reporting or bulk operations.

flowchart LR
  A[Controller] --> B[Eloquent model]
  A --> C[Query Builder]
  A --> D[Raw SQL]
  B --> E[(Database)]
  C --> E
  D --> E

Configure the connection first

Laravel reads connection settings from .env and config/database.php.

Common values:

  • DB_CONNECTION (mysql, pgsql, sqlite, sqlsrv)
  • DB_HOST, DB_PORT
  • DB_DATABASE, DB_USERNAME, DB_PASSWORD

If these are wrong, queries and migrations fail immediately, so checking them early saves time.

Use migrations as schema version control

Migrations are the source of truth for table structure in a Laravel app.

Create and run a migration:

php artisan make:migration create_posts_table
php artisan migrate

Example migration:

Schema::create('posts', function (Blueprint $table) {
    $table->id();
    $table->string('title');
    $table->text('body');
    $table->timestamps();
});

If you need to undo the latest batch:

php artisan migrate:rollback

First reads with Query Builder and Eloquent

Query Builder example:

$publishedPosts = DB::table('posts')
    ->where('is_published', true)
    ->orderByDesc('created_at')
    ->get();

Eloquent example:

$publishedPosts = Post::query()
    ->where('is_published', true)
    ->latest()
    ->get();

Both are valid. Eloquent is usually easier to keep readable in app code.

A practical request flow

flowchart TD
  A[HTTP request] --> B[Controller action]
  B --> C[Run model or query builder query]
  C --> D[Data from database]
  D --> E[Return Blade view or JSON]

In the next lessons, you will go deeper into models, relationships, and query decisions. For now, focus on this baseline: configure DB, version schema with migrations, and fetch data cleanly.

From Laravel best practices — What is Laravel?