NTM Solutions

Thứ Sáu, 24 tháng 7, 2026

🚀 Laravel 12 (2026) — Bài 18 — Request

Sau khi đã học xong Eloquent ORM và các Relationship, chúng ta sẽ chuyển sang phần Form.

Trong mọi ứng dụng web, người dùng luôn gửi dữ liệu lên máy chủ thông qua biểu mẫu (Form), URL hoặc API. 

Laravel cung cấp lớp Request để tiếp nhận và xử lý những dữ liệu này một cách đơn giản và an toàn.

Ở bài này, chúng ta sẽ tìm hiểu cách lấy dữ liệu từ Request trước khi chuyển sang Validation ở bài tiếp theo.


Request là gì?

Request là đối tượng đại diện cho một yêu cầu HTTP gửi đến Laravel.

Ví dụ người dùng:

  • Mở một trang web.

  • Gửi biểu mẫu thêm bài viết.

  • Nhấn nút tìm kiếm.

  • Cập nhật thông tin cá nhân.

Tất cả dữ liệu đều được Laravel đóng gói trong đối tượng Request.


Import Request

Trong Controller:

use Illuminate\Http\Request;

Ví dụ:

use Illuminate\Http\Request;

class PostController extends Controller
{
    public function store(Request $request)
    {

    }
}

Laravel sẽ tự động truyền đối tượng Request vào phương thức.


Tạo Form thêm Post

Ví dụ trong Blade resources/views/posts/create.blade.php :

<form action="{{ route('posts.store') }}" method="POST">

    @csrf

    <input
        type="text"
        name="title"
        placeholder="Tiêu đề">

    <textarea
        name="content"
        placeholder="Nội dung"></textarea>

    <select name="category_id">

        @foreach($categories as $category)

            <option value="{{ $category->id }}">
                {{ $category->name }}
            </option>

        @endforeach

    </select>

    <button type="submit">
        Lưu bài viết
    </button>

</form>

Danh sách Category chính là dữ liệu đã được tạo bằng Seeder ở các bài trước.


Lấy toàn bộ dữ liệu

Trong Controller:

use App\Models\Category;
/**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //Tạo form nhập thông tin post
        $categories = Category::all();

        return view(
            'posts.create',
            compact('categories')
        );
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        //xảy ra sau khi bấm nút Save
        dd($request->all());
    } 

Và route:

use App\Http\Controllers\PostController;

Route::resource(
    'posts',
    PostController::class
);
//kiểm tra route php artisan route:list 

Kiểm tra route đã tồn tại chưa

Chạy:

php artisan route:list

Nếu thấy dòng tương tự:

GET|HEAD   posts/create   posts.create

thì bạn chỉ cần mở:

http://127.0.0.1:8000/posts/create

Ví dụ kết quả :http://127.0.0.1:8000/posts/create

[
    "title" => "Laravel 12",
    "content" => "...",
    "category_id" => 2,
]

Lấy một trường

public function store(Request $request)
{
    $title = $request->input('title');

    dd($title);
}

Hoặc:

$title = $request->title;

Hai cách đều hợp lệ.


Giá trị mặc định

Nếu trường không tồn tại:

$status = $request->input(
    'status',
    0
);

Nếu không gửi status, Laravel sẽ trả về 0.


Kiểm tra dữ liệu

if ($request->has('title')) {

    echo "Có tiêu đề";

}

Kiểm tra nhiều trường:

$request->has([
    'title',
    'content'
]);

Chỉ lấy một số trường

$data = $request->only([
    'title',
    'content'
]);

Hoặc:

$data = $request->except([
    '_token'
]);

Điều này rất hữu ích khi lưu dữ liệu vào Model.


Tạo Post

Ví dụ:

use App\Models\Post;
use Illuminate\Http\Request;

public function store(Request $request)
{
    Post::create([
        'title' => $request->title,
        'content' => $request->content,
        'category_id' => $request->category_id,
        'user_id' => 1,
    ]);

    return 'Tạo Post thành công!';//return redirect()->route('posts.index');
} 

Model Post phải cho phép gán dữ liệu

// app/Models/Post.php

protected $fillable = [
    'title',
    'content',
    'category_id',
    'user_id',
];

Nếu không sẽ báo lỗi.

Trong dự án có đăng nhập, user_id thường lấy từ tài khoản đang đăng nhập. 

Ở giai đoạn hiện tại của khóa học, chúng ta tạm gán một giá trị cố định để tập trung vào cách xử lý Request.


Tìm kiếm Post

Request không chỉ dùng cho Form.

Ví dụ URL:

/posts?keyword=Laravel 

Route

Route::resource('posts', PostController::class);

Form tìm kiếm

Trong resources/views/posts/index.blade.php

<form action="{{ route('posts.index') }}" method="GET">

    <input
        type="text"
        name="keyword"
        placeholder="Nhập tiêu đề">

    <button type="submit">
        Tìm kiếm
    </button>

</form>

Controller

use Illuminate\Http\Request;
use App\Models\Post;

public function index(Request $request)
{
    $keyword = $request->keyword;

    $posts = Post::where(
        'title',
        'like',
        "%{$keyword}%"
    )->get();

    return view(
        'posts.index',
        compact('posts')
    );
}

Hiển thị kết quả

@foreach($posts as $post)

    <h3>{{ $post->title }}</h3>

@endforeach

Người dùng nhập từ khóa, Laravel sẽ lấy dữ liệu từ URL và tìm kiếm bài viết.


Lấy Category

Ví dụ:

/posts?category=2

Post Controller:

public function index(Request $request)
{
    $category = $request->category;

    $posts = Post::where(
        'category_id',
        $category
    )->get();

    return view(
        'posts.index',
        compact('posts')
    );
}

Nhờ vậy có thể lọc bài viết theo danh mục đã tạo bằng Seeder.


Request và Relationship

1. Trong create()

Truyền danh sách Tag sang View:

use App\Models\Tag;

public function create()
{
    $categories = Category::all();
    $tags = Tag::all();

    return view(
        'posts.create',
        compact('categories', 'tags')
    );
}

2. Trong Blade create

<select
    name="tags[]"
    multiple>

    @foreach($tags as $tag)

        <option value="{{ $tag->id }}">
            {{ $tag->name }}
        </option>

    @endforeach

</select>

Người dùng chọn nhiều Tag rồi bấm Lưu bài viết.


3. Trong store()

Phải tạo Post trước.

$post = Post::create([

    'title' => $request->title,

    'content' => $request->content,

    'category_id' => $request->category_id,

    'user_id' => 1,

]);

4. Sau đó mới gắn Tag

$tagIds = $request->tags;

$post->tags()->sync($tagIds);

Hoặc gọn hơn:

$post->tags()->sync(
    $request->tags
);

Đây chính là cách kết hợp Request với Relationship Many To Many đã học ở bài trước.


Request và Profile

Ví dụ cập nhật Profile:

use App\Models\Profile;
use Illuminate\Http\Request;

public function update(
    Request $request,
    Profile $profile
)
{
    $profile->update([

        'phone' => $request->phone,

        'address' => $request->address,

    ]);

    return 'Cập nhật thành công!';
}

Hoặc nếu chưa học Route Model Binding, có thể dùng ví dụ đơn giản hơn:

$profile = Profile::find(1);

$profile->update([

    'phone' => $request->phone,

    'address' => $request->address,

]);

Muốn chạy được còn cần Form

<form
    action="{{ route('profiles.update', 1) }}"
    method="POST">

    @csrf
    @method('PUT')

    <input
        type="text"
        name="phone">

    <input
        type="text"
        name="address">

    <button>
        Cập nhật
    </button>

</form>

Các trường phoneaddress thuộc bảng profiles mà chúng ta đã tạo trong phần Relationship.

Thực ra ví dụ này không nên có trong Bài 18 (Request). Nó kéo theo quá nhiều kiến thức chưa học.

Để chạy được, bạn phải có:

  • ProfileController

  • Route::resource('profiles', ProfileController::class)

  • edit.blade.php

  • ✅ Route profiles.update

  • ✅ Form PUT

  • ✅ Có bản ghi profiles.id = 1

  • ✅ Đã học Route Model Binding (hoặc find())

Trong khi bài này chỉ đang dạy Request.


Nếu vẫn muốn demo thì phải làm như sau

Route

Route::resource(
    'profiles',
    ProfileController::class
);

Mở Form

http://127.0.0.1:8000/profiles/1/edit

Laravel gọi

edit(Profile $profile)

Form

<form
    action="{{ route('profiles.update', $profile) }}"
    method="POST">

    @csrf
    @method('PUT')

    <input
        type="text"
        name="phone"
        value="{{ $profile->phone }}">

    <input
        type="text"
        name="address"
        value="{{ $profile->address }}">

    <button>
        Cập nhật
    </button>

</form>

Bấm Cập nhật

Laravel gửi

PUT /profiles/1

và mới gọi

public function update(
    Request $request,
    Profile $profile
)
{
    $profile->update([

        'phone' => $request->phone,

        'address' => $request->address,

    ]);

    return 'Cập nhật thành công!';
}

Nhưng mình khuyên không nên đưa ví dụ này vào Bài Request

Lý do là người học sẽ gặp hàng loạt câu hỏi:

  • profiles.update ở đâu?

  • ProfileController ở đâu?

  • Sao lại PUT?

  • Sao URL là /profiles/1?

  • Sao không phải /profiles/update?

  • $profile lấy ở đâu?

Trong khi bài học chỉ muốn giới thiệu:

$request->phone
$request->address

Mình sẽ bỏ hẳn ví dụ này

Đến bài CRUD Update hoặc Resource Controller, lúc đó mới dùng:

$profile->update([
    'phone' => $request->phone,
    'address' => $request->address,
]);

Còn trong Bài 18 – Request, các ví dụ về:

  • store() (tạo Post)

  • GET /posts?keyword=Laravel

  • GET /posts?category=2

  • tags[]$request->tags

đã đủ để minh họa hầu hết các cách lấy dữ liệu từ Request

Ví dụ Profile không bổ sung thêm kiến thức mới về Request, nhưng lại đòi hỏi nhiều kiến thức khác chưa học, nên dễ làm người đọc rối hơn là giúp họ hiểu.

✅ Đưa sang Bài 26 – CRUD Posts (hoặc nếu sau này có một bài CRUD Profile thì đưa vào đó).


Một số phương thức thường dùng

Phương thứcÝ nghĩa
all()Lấy toàn bộ dữ liệu
input()Lấy một trường
has()Kiểm tra trường tồn tại
only()Chỉ lấy các trường được chỉ định
except()Loại bỏ một số trường
method()Lấy phương thức HTTP
isMethod()Kiểm tra phương thức HTTP

Ví dụ:

if ($request->isMethod('post')) {

    echo 'Đây là POST';

}

Tổng kết

Trong bài này chúng ta đã học:

  • Request là gì.

  • Lấy dữ liệu từ Form.

  • Lấy dữ liệu từ URL.

  • all().

  • input().

  • has().

  • only().

  • except().

  • Kết hợp Request với Eloquent và Relationship.

Request là bước đầu tiên trong quá trình xử lý dữ liệu người dùng trước khi lưu vào cơ sở dữ liệu.


Bài tập

  1. Tạo Form thêm Post gồm tiêu đề, nội dung và Category.

  2. Hiển thị toàn bộ dữ liệu bằng dd($request->all()).

  3. Lưu Post mới vào cơ sở dữ liệu.

  4. Viết chức năng tìm kiếm Post theo tiêu đề bằng Request.

  5. Lọc danh sách Post theo Category.

  6. Cho phép chọn nhiều Tag và liên kết với Post bằng sync().


Bài tiếp theo

Ở bài sau, chúng ta sẽ tìm hiểu Validation, cách kiểm tra dữ liệu đầu vào để đảm bảo người dùng nhập đúng định dạng trước khi lưu vào cơ sở dữ liệu.

x1

quay về MỤC LỤC

Không có nhận xét nào:

Đăng nhận xét

Facebook Youtube RSS