Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Query Builder Tutorial in Laravel

Introduction to Query Builder

Laravel's Query Builder provides a convenient, fluent interface to creating and running database queries. It is a powerful tool that allows you to build complex SQL queries without needing to write raw SQL.

The Query Builder can be used to select data from a database, insert new records, update existing records, and delete records.

Getting Started

Before you can start using the Query Builder, you need to ensure that you have set up your database connection in the Laravel application. This is done in the .env file.

Example of .env Database Configuration:

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

Basic Queries

To get started with basic select queries, you can use the DB::table() method.

Example of a Basic Select Query:

$users = DB::table('users')->get();

This will retrieve all records from the users table.

Building Queries

The Query Builder provides a fluent interface for building queries. You can chain methods to add constraints to your queries.

Example of a Chained Query:

$users = DB::table('users')
    ->where('active', 1)
    ->orderBy('name', 'asc')
    ->get();

This retrieves all active users from the users table and orders them by name in ascending order.

Inserting Records

Inserting records into the database can be done using the insert() method.

Example of Inserting a New User:

DB::table('users')->insert([
    'name' => 'John Doe',
    'email' => 'john@example.com',
    'password' => Hash::make('password123')
]);

Updating Records

To update existing records, you can use the update() method.

Example of Updating a User's Email:

DB::table('users')
    ->where('name', 'John Doe')
    ->update(['email' => 'john.doe@example.com']);

Deleting Records

To delete records from the database, you can use the delete() method.

Example of Deleting a User:

DB::table('users')
    ->where('name', 'John Doe')
    ->delete();

Conclusion

Laravel's Query Builder is a powerful feature that simplifies database interactions. By using it, you can build complex queries with ease while keeping your code clean and readable.

Experiment with various methods and combinations to get the most out of the Query Builder and enhance your Laravel applications.