Laravel’s Query Builder provides a powerful, fluent interface for building SQL queries in PHP. It allows you to interact with the database in an expressive, SQL-like syntax while abstracting away most of the complexity.
We’ll walk through a typical use case in a Laravel application using Query Builder for various tasks like selecting, inserting, updating, and deleting data.
If you don’t have a Laravel project, you can set one up as follows:
composer create-project --prefer-dist laravel/laravel laravel-query-builder cd laravel-query-builder php artisan serve
Ensure you set up your database configuration in the .env file:
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=your_database DB_USERNAME=your_username DB_PASSWORD=your_password
Run migrations for creating default tables:
php artisan migrate
Let’s create a controller to demonstrate the usage of Query Builder:
php artisan make:controller UserController
Edit UserController.php with the following code:
<?php namespace App\Http\Controllers; use Illuminate\Support\Facades\DB; use Illuminate\Http\Request; class UserController extends Controller { // Fetching all users from the users table public function index() { // Step 3: Select all users $users = DB::table('users')->get(); return response()->json($users); } // Insert a new user public function store(Request $request) { // Step 4: Insert a new user DB::table('users')->insert([ 'name' => $request->name, 'email' => $request->email, 'password' => bcrypt($request->password), ]); return response()->json(['message' => 'User created successfully!']); } // Update an existing user public function update(Request $request, $id) { // Step 5: Update user by ID DB::table('users') ->where('id', $id) ->update([ 'name' => $request->name, 'email' => $request->email, ]); return response()->json(['message' => 'User updated successfully!']); } // Delete a user public function destroy($id) { // Step 6: Delete user by ID DB::table('users')->where('id', $id)->delete(); return response()->json(['message' => 'User deleted successfully!']); } }
Use Query Builder to select all rows from the users table:
$users = DB::table('users')->get();
Example Response:
[ { "id": 1, "name": "John Doe", "email": "john@example.com" }, { "id": 2, "name": "Jane Doe", "email": "jane@example.com" } ]
Insert a new user using Query Builder:
DB::table('users')->insert([ 'name' => 'Alice', 'email' => 'alice@example.com', 'password' => bcrypt('password123'), ]);
This adds a new user to the users table.
To update an existing record, use update():
DB::table('users') ->where('id', 1) ->update([ 'name' => 'John Smith', 'email' => 'johnsmith@example.com' ]);
This updates the user with ID 1 in the users table.
To delete a record from the database, use delete():
DB::table('users')->where('id', 2)->delete();
This deletes the user with ID 2.
You can chain additional methods to filter the data or add conditions to the query.
$users = DB::table('users') ->where('email', 'like', '%example.com%') ->orderBy('name', 'asc') ->get();
Laravel’s Query Builder makes it easy to paginate results.
$users = DB::table('users')->paginate(10);
Use database transactions to ensure that multiple queries are executed successfully. If one query fails, all changes are rolled back.
DB::transaction(function () { DB::table('users')->insert([ 'name' => 'John Doe', 'email' => 'john@example.com', 'password' => bcrypt('password123') ]); DB::table('orders')->insert([ 'user_id' => 1, 'order_total' => 500 ]); });
If you need to run raw SQL, Laravel’s Query Builder allows it:
$users = DB::select('SELECT * FROM users WHERE id = ?', [1]);
Laravel’s Query Builder offers a powerful and flexible way to interact with your database, abstracting away much of the SQL complexity. By breaking down each part—retrieving, inserting, updating, deleting, filtering, and more—you can easily manage your database interactions in a clean and organized way.
This example provides a basic guide to Query Builder. As your application grows, you can use more advanced features such as joins, subqueries, and eager loading with Eloquent.
The above is the detailed content of Getting Started with Laravel: A Beginners Guide to Query Builder. For more information, please follow other related articles on the PHP Chinese website!