public function export() {
return response()
->download('file.csv', 'export.csv', ['header' => 'value']);
}
public function otherExport() {
return response()->download('file.pdf');
}
public function contacts() {
return response()->json(Contact::all());
}
public function jsonpContacts(Request $request) {
return response()
->json(Contact::all())
->setCallback($request->input('callback'));
}
public function nonEloquentContacts() {
return response()->json(['Tom', 'Jerry']);
}
Example 10-11. Examples of using the redirect() global helper
return redirect('account/payment');
return redirect()->to('account/payment');
return redirect()->route('account.payment');
return redirect()->action('AccountController@showPayment');
// If redirecting to an external domain
return redirect()->away('https://tighten.co');
// If named route or controller needs parameters
return redirect()->route('contacts.edit', ['id' => 15]);
return redirect()->action('ContactsController@edit', ['id' => 15]);
你也可以重定向”回“之前的页面,当处理和验证用户输入特别有用,如示例10-12显示了验证例子。
Example 10-12. Redirect back with input
public function store() {
// If validation fails...
return back()->withInput();
}
最后,你可以在重定向的同时闪存数据到session,通常携带错误或者成功消息,如示例10-13。
Example 10-13. Redirect with flashed data
Route::post('contacts', function () {
// Store the contact
return redirect('dashboard')->with('message', 'Contact created!');
});
Route::get('dashboard', function () {
// Get the flashed data from session--usually handled in Blade template
echo session('message');
});
class AppServiceProvider {
public function boot() {
Response::macro('myJson', function ($content) {
return response(json_encode($content))
->withHeaders(['Content-Type' => 'application/json']);
});
}
Example 10-15. Creating a simple Responsable object
use Illuminate\Contracts\Support\Responsable;
class MyJson implements Responsable {
public function __construct($content) {
$this->content = $content;
}
public function toResponse() {
return response(json_encode($this->content))
->withHeaders(['Content-Type' => 'application/json']);
}
Example 10-16. Using Responsable to create a view object
use Illuminate\Contracts\Support\Responsable;
class GroupDonationDashboard implements Responsable {
public function __construct($group) {
$this->group = $group;
}
public function budgetThisYear() {
// ...
}
public function giftsThisYear() {
// ...
}
public function toResponse() {
return view('groups.dashboard')
->with('annual_budget', $this->budgetThisYear())
->with('annual_gifts_received', $this->giftsThisYear());
}