Response trong tiếng Anh có nghĩa là “lời phản hồi“. Còn trong lập trình Web, HTTP Response được gọi là “thông báo phản hồi HTTP“. Đây là kết quả server trả về cho client.
Route::get('/', function () { return 'Hello World'; }); Route::get('/', function () { return ['a' => 1, 'b' => 2, 'c' => 3]; });
Thông thường Responses sẽ trả về chuỗi hoặc mảng dữ liệu.
return response($content) ->header('Content-Type', $type) ->cookie('name', 'value', $minutes);
Phương thức cookie có thể truyển nhiều đối số hơn.
->cookie($name, $value, $minutes, $path, $domain, $secure, $httpOnly)
Route::get('dashboard', function () { return redirect('home/dashboard'); }); //trả về trang trước Route::post('user/profile', function () { // Validate the request... return back()->withInput(); }); //Chuyển đến route có tên là login return redirect()->route('login'); //--nếu có tham số return redirect()->route('profile', ['id' => 1]);
Nếu bạn chưa biết đến Controller hãy tìm hiểu tại bài viết Controller và View trong Laravel nhé!
return redirect()->action('HomeController@index'); //nếu phương thức cần tham số thì return redirect()->action( 'UserController@profile', ['id' => 1] );
return redirect()->away('https://www.google.com'); //Chuyển trang có kèm tạo session Route::post('user/profile', function () { // Update the user's profile... return redirect('dashboard')->with('status', 'Profile updated!'); });
//trả về trang giao diện return response() ->view('hello', $data, 200) ->header('Content-Type', $type); //trả về chuỗi JSON return response()->json([ 'name' => 'Abigail', 'state' => 'CA' ]); //trả về download file return response()->download($pathToFile); return response()->download($pathToFile, $name, $headers); return response()->download($pathToFile)->deleteFileAfterSend(); //trả về file return response()->file($pathToFile); return response()->file($pathToFile, $headers);
Một lưu ý nhỏ cho các bạn là khi sử dụng Responses mình có thể không cần gọi response(). Ví dụ: return view();
Mình đã hướng dẫn các bạn Responses trong Laravel. Và đến đây thì bạn có thể tạo cho mình một API rồi cùng xem bài viết API với PHP và với Framework Laravel. Bài viết sau mình sẽ hướng dẫn các bạn Tạo URL trong Laravel 6 hết sức là chi tiết cùng xem nhé!