- vừa được xem lúc

HTTP Responses

0 0 4

Người đăng: Ngô Quốc Hùng

Theo Viblo Asia

Creating Responses

Strings & Arrays

Route::get('/', function () { return 'Hello World';
}); Route::get('/', function () { return [1, 2, 3];
});

Response Objects

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

Eloquent Models & Collections

use App\Models\User; Route::get('/user/{user}', function (User $user) { return $user;
});

Attaching Headers To Responses

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

Cache Control Middleware

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

Attaching Cookies To Responses

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

Generating Cookie Instances

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

Expiring Cookies Early

return response('Hello World')->withoutCookie('name'); Cookie::expire('name');

Cookies & Encryption

  • Mặc định tất cả cookie sinh ra bởi Laravel sẽ được encrypted và signed.
  • Có thể bỏ qua bằng cách khai báo vào thuộc tính $except trong App\Http\Middleware\EncryptCookies
/** * The names of the cookies that should not be encrypted. * * @var array */
protected $except = [ 'cookie_name',
];

Redirects

Route::get('/dashboard', function () { return redirect('home/dashboard');
}); Route::post('/user/profile', function () { // Validate the request... return back()->withInput();
});

Redirecting To Named Routes

return redirect()->route('login'); // For a route with the following URI: /profile/{id} return redirect()->route('profile', ['id' => 1]);

Populating Parameters Via Eloquent Models

  • Trong trường hợp route redirect với tham số id thay vì truyền trực tiếp id ta có thể truyền một Eloquent model để thay thế, id sẽ được tự động truy xuất
// For a route with the following URI: /profile/{id} return redirect()->route('profile', [$user]);

Redirecting To Controller Actions

use App\Http\Controllers\UserController; return redirect()->action([UserController::class, 'index']); return redirect()->action( [UserController::class, 'profile'], ['id' => 1]
);

Redirecting To External Domains

  • Đôi khi bạn muốn redirect đến 1 domain ngoài ứng dụng của mình, có thể sử dụng method away()
return redirect()->away('https://www.google.com');

Redirecting With Flashed Session Data

Route::post('/user/profile', function () { // ... return redirect('dashboard')->with('status', 'Profile updated!');
});
  • Blade syntax
@if (session('status')) <div class="alert alert-success"> {{ session('status') }} </div>
@endif

Redirecting With Input

return back()->withInput();

Other Response Types

View Responses

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

JSON Responses

return response()->json([ 'name' => 'Abigail', 'state' => 'CA',
]); return response() ->json(['name' => 'Abigail', 'state' => 'CA']) ->withCallback($request->input('callback'));

File Downloads

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

Streamed Downloads

  • Nếu bạn muốn biến response trở thành download respone mà không cần lưu vào ổ đĩa dưới dạng 1 file:
use App\Services\GitHub; return response()->streamDownload(function () { echo GitHub::api('repo') ->contents() ->readme('laravel', 'laravel')['contents'];
}, 'laravel-readme.md');

File Responses

  • Để hiện thị file
return response()->file($pathToFile); return response()->file($pathToFile, $headers);

Response Macros

  • Nếu bạn muốn custom response để có thể tái sử dụng ở nhiều route hoặc controller thì bạn nên sử dụng macro method của Response facade. Cùng vớ đó là việc bạn cần phải gọi đến chúng trong phương thức boot của 1 trong những `service prodiders:
<?php namespace App\Providers; use Illuminate\Support\Facades\Response;
use Illuminate\Support\ServiceProvider; class AppServiceProvider extends ServiceProvider
{ /** * Bootstrap any application services. * * @return void */ public function boot() { Response::macro('caps', function ($value) { return Response::make(strtoupper($value)); }); }
}
  • Khi đó trong route hoặc controller bạn có thể dùng response helper để gọi như sau:
return response()->caps('foo');

Bình luận

Bài viết tương tự

- vừa được xem lúc

RECAPTCHAV3 trong Laravel 9

Recaptcha của google là công cụ miễn phí và hiệu quả để chống lại Spam request - DDOS tới trang wed của bạn. Mình add recaptcha vào dự án đã dựng sẵn, các bạn nào chưa có dự án thì cứ tìm kiếm và dựng

0 0 19

- vừa được xem lúc

Mail trong Laravel

Giới thiệu. Trong Laravel có thể gửi mail theo nhiều cách (driver) khác nhau như SMTP, Mailgun, Postmark, Amazon SES …Bạn có thể gửi các transaction mail (mail giao dịch) như Postmark hoặc các mail vớ

0 0 15

- vừa được xem lúc

Middleware trong Laravel

Giới thiệu. . . Middleware là những đoạn mã trung gian nằm giữa các request và response.

0 0 20

- vừa được xem lúc

Hướng dẫn search column trong laravel-datatables với package yajra/laravel-datatables

Link install package ở đây: https://yajrabox.com/docs/laravel-datatables/master/ .

0 0 15

- vừa được xem lúc

Task Scheduling trong Laravel

Giới thiệu. .

0 0 14

- vừa được xem lúc

Laravel Request

Introduction. .

0 0 5