首页 > 后端开发 > php教程 > Getting Started with Laravel: A Beginner&#s Guide to Query Builder

Getting Started with Laravel: A Beginner&#s Guide to Query Builder

Susan Sarandon
发布: 2024-09-23 06:22:02
原创
718 人浏览过

Getting Started with Laravel: A Beginner

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.


Step 1: Setup Laravel Project

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
登录后复制

Step 2: Use Query Builder in a Controller

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!']);
    }
}
登录后复制

Step 3: Retrieve Data

Use Query Builder to select all rows from the users table:

$users = DB::table('users')->get();
登录后复制
  • Description:
    • The DB::table('users') method targets the users table.
    • The get() method retrieves all records from that table.

Example Response:

[
    {
        "id": 1,
        "name": "John Doe",
        "email": "john@example.com"
    },
    {
        "id": 2,
        "name": "Jane Doe",
        "email": "jane@example.com"
    }
]
登录后复制

Step 4: Insert Data

Insert a new user using Query Builder:

DB::table('users')->insert([
    'name' => 'Alice',
    'email' => 'alice@example.com',
    'password' => bcrypt('password123'),
]);
登录后复制
  • Description:
    • The insert() method inserts a new row into the users table.
    • The data is passed as an associative array where the keys match the column names.

This adds a new user to the users table.


Step 5: Update Data

To update an existing record, use update():

DB::table('users')
    ->where('id', 1)
    ->update([
        'name' => 'John Smith',
        'email' => 'johnsmith@example.com'
    ]);
登录后复制
  • Description:
    • The where() clause selects the row with id = 1.
    • The update() method modifies the name and email fields for the selected row.

This updates the user with ID 1 in the users table.


Step 6: Delete Data

To delete a record from the database, use delete():

DB::table('users')->where('id', 2)->delete();
登录后复制
  • Description:
    • The where() clause specifies the condition to select the user with ID 2.
    • The delete() method removes the matching row from the table.

This deletes the user with ID 2.


Step 7: Filtering with Query Builder

You can chain additional methods to filter the data or add conditions to the query.

Example: Retrieve users with a specific condition

$users = DB::table('users')
    ->where('email', 'like', '%example.com%')
    ->orderBy('name', 'asc')
    ->get();
登录后复制
  • Description:
    • The where() clause adds a condition, fetching users whose email contains example.com.
    • The orderBy() method sorts the users by name in ascending order.

Step 8: Pagination

Laravel’s Query Builder makes it easy to paginate results.

$users = DB::table('users')->paginate(10);
登录后复制
  • Description:
    • The paginate() method breaks the results into pages, displaying 10 results per page.

Step 9: Transactions

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
    ]);
});
登录后复制
  • Description:
    • The transaction() method ensures that both the users and orders table inserts are executed successfully. If either fails, both operations will be rolled back.

Step 10: Raw Queries

If you need to run raw SQL, Laravel’s Query Builder allows it:

$users = DB::select('SELECT * FROM users WHERE id = ?', [1]);
登录后复制
  • Description:
    • The select() method can be used to execute raw SQL queries.
    • It uses prepared statements (?) for security, preventing SQL injection.

Conclusion

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.

以上是Getting Started with Laravel: A Beginner&#s Guide to Query Builder的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板