Урок 11

Ответы и редиректы

Контроллер возвращает ответ, который отправляется клиенту. Laravel поддерживает разные типы ответов.

Строки и массивы

return 'Hello';
return ['status' => 'ok'];

Массив автоматически преобразуется в JSON.

View

return view('posts.index', ['posts' => $posts]);
return view('posts.show', compact('post'));

JSON

return response()->json(['status' => 'ok']);
return response()->json($data, 201);
return response()->json(['error' => 'Not found'], 404);

Пустой ответ

return response()->noContent(); // 204

Коды статусов

  • 200 — OK
  • 201 — Created
  • 204 — No Content
  • 301 — Moved Permanently
  • 302 — Found (обычный редирект)
  • 400 — Bad Request
  • 401 — Unauthorized
  • 403 — Forbidden
  • 404 — Not Found
  • 422 — Unprocessable Entity (ошибки валидации)
  • 500 — Internal Server Error

Редиректы

return redirect('/home');
return redirect()->route('posts.index');
return redirect()->action([PostController::class, 'index']);
return back();
return redirect()->away('https://example.com');

Flash-сообщения

return redirect()->route('posts.index')->with('success', 'Сохранено');
return back()->withInput()->withErrors(['title' => 'Ошибка']);

withInput() сохраняет введённые данные. withErrors() — ошибки.

Скачивание файлов

return response()->download($path, 'file.pdf');
return response()->file($path);

Кеширование

return response('content')->header('Cache-Control', 'max-age=3600');

View с заголовками

return response()->view('posts.index', $data)
    ->header('X-Custom', 'value');