Học Laravel – Bài 16: HTTP Response

Tạo response

String & Array:

Tất cả route và controller nên trả về 1 response để gửi lại cho user. Laravel cung cấp nhiều cách để trả về response. Response cơ bản nhất là trả về string. Framework sẽ tự động convert string thành HTTP response:

PHP
Route::get('/', function() {
    return 'Hello world'; 
});

Bạn cũng có thể return array. Framework sẽ tự động convert thành JSON response:

PHP
Route::get('/', function() {
    return [1, 2, 5];
});

Bạn cũng có thể return Eloquent collections. Nó sẽ tự động convert thành JSON.

Response object:

Bạn có thể return 1 instance của Illuminate\Http\Response hoặc view.

Return Response instance cho phép bạn customize HTTP code và header. Response cung cấp nhiều method để build HTTP response:

PHP
Route::get('/home', function() {
    return response('Hello World', 200)->header('Content-Type', 'text/plain');
});

Eloquent Model và Collection:

Bạn có thể return Eloquent ORM model và collections trực tiếp từ route và controller. Khi đó Laravel sẽ tự động convert model và collection thành JSON response:

PHP
Route::get('/user/{user}', function(User $user) {
    return $user;
});

Đính kèm header vào response:

Sử dụng method header để thêm các header vào response trước khi gửi về cho user:

PHP
return response($content)
    ->header('Content-Type', $type)
    ->header('X-Header-One', 'Header Value');

Sử dụng method withHeaders để chỉ định 1 array header được thêm vào response:

PHP
return response($content)
    ->withHeaders([
        'Content-Type' => $type,
        'X-Header-One' => 'Value',
    ]);

Cache control middleware:

Laravel có sẵn middleware cache.headers, được sử dụng để set nhanh Cache-control header cho 1 nhóm route. Nếu etag được chỉ định trong danh sách chỉ thị, 1 mã MD5 sẽ được set làm định danh ETag:

PHP
Route::middleware('cache.headers:public;max_age=2628000;etag')->group(function () {
    Route::get('/privacy', function () {
        // ...
    });
 
    Route::get('/terms', function () {
        // ...
    });
});

Đính kèm cookie vào response:

Bạn có thể đính kèm cookie vào Response sử dụng method cookie:

PHP
return response('Hello World')->cookie('name', 'value', $minutes);

// tham số tùy chọn:
->cookie('name', 'value', $minutes, $path, $domain, $secure, $httpOnly);

Nếu bạn muốn đảm bảo cookie được gửi với response nhưng bạn không có instance của response đó, bạn có thể sử dụng Cookie facade để “queue” cookie cho đính kèm vào response khi nó được gửi đi. Method queue chấp nhận tham số cần thiết để tạo 1 cookie instance. Những cookie này sẽ được đính kèm vào response trước khi được gửi tới browser:

PHP
Cookie::queue('name', 'value', $minutes);

Khởi tạo cookie instance:

Nếu bạn muốn khởi tạo 1 instance của Symfony\Component\HttpFoundation\Cookie để có thể đính kèm vào response lần sau, bạn có thể sử dụng helper cookie. Cookie này sẽ không được gửi đến client cho đến khi nó được đính kèm vào 1 response instance:

PHP
$cookie = cookie('name', 'value', $minutes);

return response('Hello World')->cookie($cookie);

Hết hạn cookie sớm:

Bạn có thể gỡ cookie bằng cách cho hết hạn thông qua method withoutCookie:

PHP
return response('Hello World')->withoutCookie('name');

Nếu không có instance của response, dùng method expire của Cookie facade:

PHP
Cookie::expire('name');

Redirect:

Redirect response là instance của class Illuminate\Http\RedirectResponse, chứa các header thích hợp cần thiết để redirect user đến URL khác. Nhiều cách để khởi tạo RedirectResponse instance. Cách đơn giản nhất là dùng helper redirect:

PHP
Route::get('/dashboard', function() {
    return redirect('home/dashboard');
});

Thỉnh thoảng bạn muốn redirect về location trước, ví dụ khi submit form không hợp lệ. Bạn sử dụng helper back. Nếu tính năng này dùng session, đảm bảo route gọi function back đang sử dụng middleware web:

PHP
Route::post('/user/profile', function() {
    // validate request
    
    return back()->withInput();
});

Redirect về route đã được đặt tên:

Khi bạn gọi helper redirect không có tham số, 1 instance được trả về, cho phép bạn gọi bất kỳ method nào. Ví dụ, để khởi tạo 1 RedirectResponse đến 1 route đã được đặt tên, sử dụng method route:

PHP
return redirect()->route('login');

Nếu route có tham số, bạn có thể pass chúng như 1 tham số thứ 2 cho method route:

PHP
return redirect()->route('profile', ['id' => 1]);

Trú ngụ tham số thông qua Eloquent Models:

Nếu bạn đang redirect đến 1 route với 1 tham số “ID” ở trong Eloquent model, bạn có thể pass chính model đó. ID sẽ được extract tự động:

PHP
return redirect()->route('profile', [$user]);

Nếu bạn muốn customize giá trị được đặt trong tham số của route, bạn có thể chỉ định cột trong định nghĩa tham số route (profile/{id:slug}) hoặc bạn có thể override method getRouteKey trong Eloquent model:

PHP
public function getRouteKey(): mixed
{
    return $this->slug;
}

Redirect đến controller action:

Bạn có thể redirect đến controller action bằng cách pass controller và tên action trong action method:

PHP
return redirect()->action([UserController::class, 'index']);

Nếu controller cần tham số, bạn có thể pass nó như một đối số thứ 2 cho method action:

PHP
return redirect()->action(
    [UserController::class, 'profile'], ['id' => 1]
);

Redirect đến domain ngoài:

PHP
return redirect()->away('https://www.google.com');

Redirect với flashed session:

PHP
return redirect('dashboard')->with('status', 'Profile updated!');

Sau khi user đã redirect, bạn có thể hiển thị flashed message từ session. Ví dụ sử dụng Blade:

PHP
@if (session('status'))
    <div class="alert alert-success">{{ session('status') }}</div>
@endif

Redirect với input:

Bạn có thể sử dụng method withInput để flash input của request hiện tại vào session trước khi redirect. Một khi input được flash vào session, bạn có thể truy xuất ở request tiếp theo:

PHP
return back()->withInput();

Một số dạng response khác:

View response:

PHP
return response()->view('hello', $data, 200)
                ->header('Content-Type', $type);

Nếu không cần pass HTTP status code hoặc custom header, bạn có thể dùng hàm view.

JSON response:

Method json sẽ tự động set Content-Type header thành application/json, cũng như convert array đã cho thành JSON:

PHP
return response()->json([
    'name' => 'Abigail',
    'state' => 'CA'
]);

File download:

Method download sẽ khởi tạo 1 response chỉ thị cho trình duyệt download file. Method download chấp nhận filename là tham số thứ 2, cái mà sẽ xác định filename sẽ được xem bởi user:

PHP
return response()->download($pathToFile);

return response()->download($pathToFile, $name, $headers);

Để lại một bình luận

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *