Laravel return back with error

laravel redirect back with error message, laravel redirect with errors and input, laravel redirect back with input and message, redirect back with input and error laravel, redirect back with errors in laravel, laravel redirect back with validation error

October 9, 2020
Category : PHP
Laravel

Sometime, we need to redirect back to form page with input values and error messages in laravel 5 application. So if you have same require to back with validation error message or redirect back with input value then this post will help you. you can also use this example with laravel 6, laravel 7, laravel 8 and laravel 9 version.

we almost use laravel default validate method for validation because it will automatically redirect back with your previous form page. But sometime you need to set custom validation check or if condition then you can also redirect back() with error message like as default error message work.

In this post, i will give you very simple example to show you how you can redirect back with input parameter and error message.

Redirect with Error Message:

return back()->withErrors(['name.required', 'Name is required']);

Redirect with Input:

return back()->withInput();

Redirect with Input and Errors:

return back()

->withInput()

->withErrors(['name.required', 'Name is required']);

I hope it can help you…

Hardik Savani

I’m a full-stack developer, entrepreneur and owner of Aatman Infotech. I
live in India and I love to
write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery,
Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.

Follow Me:

We are Recommending you

  • Laravel 5.7 — Create REST API with authentication using Passport Tutorial
  • Laravel 5.7 Autocomplete Search from Database using Typeahead JS
  • How to check if View Exists or not in Laravel?
  • Laravel Clear Cache from Route, View, Config Example
  • How to Get Last Inserted Id in Laravel?
  • How to Send Mail using Gmail SMTP in Laravel?
  • How to Get Query Log in Laravel Eloquent?
  • How to Set URL without Http of Other Site in Laravel?

Ezoic

Ezoic

Popular Posts

  • Laravel Collection GroupBy with Examples
  • How to check uploaded file is empty or not in Laravel?
  • How to Search First Name and Last Name in Laravel Query?
  • Laravel — Class «DOMDocument» Not Found — Solved
  • Laravel — Class «AppHttpControllersValidator» not found — Solved
  • How to Generate 4,6,8,10 Digit Random number in PHP?
  • How to Subtract Hours from DateTime in PHP?
  • Multiple Database Connection in PHP Codeigniter 3
  • Laravel 7 Yajra Datatables Example
  • Laravel Phone Number Verification using Firebase Example
  • How to implement infinite ajax scroll pagination in Laravel?

Categories

  • Laravel
  • Angular
  • PHP
  • jQuery
  • Python
  • Bootstrap
  • Javascript
  • MySql
  • Ajax
  • Ubuntu
  • Node JS
  • HTML
  • Codeigniter
  • Guest Post
  • Vue.JS
  • React JS
  • Git
  • Server
  • Installation
  • JSON
  • CSS
  • .htaccess
  • Google Map
  • SQL
  • JQuery UI
  • Google API
  • Typeahead JS
  • Axios
  • Socket.io
  • Highcharts

Latest Posts

  • Ubuntu PHP bz2 Extension Install Commands Example
  • Ubuntu PHP bcmath Extension Install Commands Example
  • Ubuntu PHP ZIP Extension Install Commands Example
  • How to Install PHP XML Extension in Ubuntu?
  • How to Install PHP GD Extension in Ubuntu?

Содержание

  1. Laravel Framework Russian Community
  2. Создание ответов
  3. Строки и массивы
  4. Объекты ответа
  5. Модели и коллекции Eloquent
  6. Добавление заголовков к ответам
  7. Посредник управления кешем
  8. Добавление файлов Cookies к ответам
  9. Создание экземпляров Cookie
  10. Досрочное окончание срока действия файлов Cookies
  11. Файлы Cookies и шифрование
  12. Перенаправления
  13. Перенаправление на именованные маршруты
  14. Заполнение параметров с моделей Eloquent
  15. Перенаправление к действиям контроллера
  16. Перенаправление на внешние домены
  17. Перенаправление с кратковременным сохранением данных в сессии
  18. Перенаправление с кратковременным сохранением входных данных
  19. Другие типы ответов
  20. Ответы с HTML-шаблонами
  21. Ответы JSON
  22. Ответы для загрузки файлов
  23. Потоковые загрузки
  24. Ответы, отображающие содержимое файлов
  25. Макрокоманды ответа
  26. HTTP Responses
  27. Creating Responses
  28. Strings & Arrays
  29. Response Objects
  30. Eloquent Models & Collections
  31. Attaching Headers To Responses
  32. Cache Control Middleware
  33. Attaching Cookies To Responses
  34. Generating Cookie Instances
  35. Expiring Cookies Early
  36. Cookies & Encryption
  37. Redirects
  38. Redirecting To Named Routes
  39. Populating Parameters Via Eloquent Models
  40. Redirecting To Controller Actions
  41. Redirecting To External Domains
  42. Redirecting With Flashed Session Data
  43. Redirecting With Input
  44. Other Response Types
  45. View Responses
  46. JSON Responses
  47. File Downloads
  48. Streamed Downloads
  49. File Responses
  50. Response Macros

Создание ответов

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

Все маршруты и контроллеры должны возвращать ответ, который будет отправлен обратно в браузер пользователя. Laravel предлагает несколько разных способов вернуть ответы. Самый простой ответ – это возврат строки из маршрута или контроллера. Фреймворк автоматически преобразует строку в полный HTTP-ответ:

Помимо возврата строк из ваших маршрутов и контроллеров, вы также можете возвращать массивы. Фреймворк автоматически преобразует массив в ответ JSON:

Знаете ли вы, что можете возвращать коллекции Eloquent из ваших маршрутов или контроллеров? Они будут автоматически преобразованы в JSON.

Объекты ответа

Как правило, вы не просто будете возвращать строки или массивы из действий маршрута. Вместо этого вы вернете полные экземпляры IlluminateHttpResponse или шаблоны.

Возврат полного экземпляра Response позволяет вам настроить код состояния и заголовки HTTP ответа. Экземпляр Response наследуется от класса SymfonyComponentHttpFoundationResponse , который содержит множество методов для построения ответов HTTP:

Модели и коллекции Eloquent

По желанию можно вернуть модели и коллекции Eloquent ORM прямо из ваших маршрутов и контроллеров. Когда вы это сделаете, Laravel автоматически преобразует модели и коллекции в ответы JSON, учитывая скрытие атрибутов модели:

Добавление заголовков к ответам

Имейте в виду, что большинство методов ответа можно объединять в цепочку вызовов для гибкого создания экземпляров ответа. Например, вы можете использовать метод header для добавления серии заголовков к ответу перед его отправкой обратно пользователю:

Или вы можете использовать метод withHeaders , чтобы указать массив заголовков, которые будут добавлены к ответу:

Посредник управления кешем

Laravel содержит посредник cache.headers , используемый для быстрой установки заголовка Cache-Control для группы маршрутов. Директивы должны быть предоставлены с использованием эквивалента «snake case» соответствующей директивы управления кешем и должны быть разделены точкой с запятой. Если в списке директив указан etag , то MD5-хеш содержимого ответа будет автоматически установлен как идентификатор ETag:

Добавление файлов Cookies к ответам

Вы можете добавить Cookies к исходящему экземпляру IlluminateHttpResponse , используя метод cookie . Вы должны передать этому методу имя, значение и количество минут, в течение которых куки должен считаться действительным:

Метод cookie также принимает еще несколько аргументов, которые используются реже. Как правило, эти аргументы имеют то же назначение и значение, что и аргументы, передаваемые встроенному в PHP методу setcookie method:

Если вы хотите, чтобы куки отправлялся вместе с исходящим ответом, но у вас еще нет экземпляра этого ответа, вы можете использовать фасад Cookie , чтобы «поставить в очередь» файлы Cookies для добавления их к ответу при его отправке. Метод queue принимает аргументы, необходимые для создания экземпляра Cookie . Эти файлы Cookies будут добавлены к исходящему ответу перед его отправкой в браузер:

Создание экземпляров Cookie

Если вы хотите сгенерировать экземпляр SymfonyComponentHttpFoundationCookie , который может быть добавлен к экземпляру ответа позже, вы можете использовать глобальный помощник cookie . Этот файл Cookies не будет отправлен обратно клиенту, если он не прикреплен к экземпляру ответа:

Досрочное окончание срока действия файлов Cookies

Вы можете удалить куки, обнулив срок его действия с помощью метода withoutCookie исходящего ответа:

Если у вас еще нет экземпляра исходящего ответа, вы можете использовать метод expire фасада Cookie для обнуления срока действия кук:

Файлы Cookies и шифрование

По умолчанию все файлы Cookies, генерируемые Laravel, зашифрованы и подписаны, поэтому клиент не может их изменить или прочитать. Если вы хотите отключить шифрование для некоторого подмножества файлов Cookies, создаваемых вашим приложением, вы можете использовать свойство $except посредника AppHttpMiddlewareEncryptCookies , находящегося в каталоге app/Http/Middleware :

Перенаправления

Ответы с перенаправлением являются экземплярами класса IlluminateHttpRedirectResponse и содержат корректные заголовки, необходимые для перенаправления пользователя на другой URL. Есть несколько способов сгенерировать экземпляр RedirectResponse . Самый простой способ – использовать глобальный помощник redirect :

По желанию можно перенаправить пользователя в его предыдущее местоположение, например, когда отправленная форма является недействительной. Вы можете сделать это с помощью глобального помощника back . Поскольку эта функция использует сессии, убедитесь, что маршрут, вызывающий функцию back , использует группу посредников web :

Перенаправление на именованные маршруты

Когда вы вызываете помощник redirect без параметров, возвращается экземпляр IlluminateRoutingRedirector , что позволяет вам вызывать любой метод экземпляра Redirector . Например, чтобы сгенерировать RedirectResponse на именованный маршрут, вы можете использовать метод route :

Если ваш маршрут имеет параметры, вы можете передать их в качестве второго аргумента методу route :

Заполнение параметров с моделей Eloquent

Если вы перенаправляете на маршрут с параметром ID , который извлекается из модели Eloquent, то вы можете просто передать саму модель. ID будет извлечен автоматически:

Если вы хотите настроить значение, которое соответствует параметру маршрута, то вы можете указать столбец при определении параметра маршрута ( /profile/ ) или переопределить метод getRouteKey в вашей модели Eloquent:

Перенаправление к действиям контроллера

Вы также можете генерировать перенаправления на действия контроллера. Для этого передайте имя контроллера и действия методу action :

Если ваш маршрут контроллера требует параметров, вы можете передать их в качестве второго аргумента методу action :

Перенаправление на внешние домены

Иногда может потребоваться перенаправление на домен за пределами вашего приложения. Вы можете сделать это, вызвав метод away , который создает RedirectResponse без какой-либо дополнительной кодировки URL, валидации или проверки:

Перенаправление с кратковременным сохранением данных в сессии

Перенаправление на новый URL-адрес и краткосрочная запись данных в сессию обычно выполняются одновременно. Обычно это делается после успешного выполнения действия, когда вы отправляете сообщение об успешном завершении в сессию. Для удобства вы можете создать экземпляр RedirectResponse и передать данные в сессию в единой текучей цепочке методов:

После перенаправления пользователя, вы можете отобразить сохраненное из сессии сообщение. Например, используя синтаксис Blade:

Перенаправление с кратковременным сохранением входных данных

Вы можете использовать метод withInput экземпляра RedirectResponse , для передачи входных данных текущего запроса в сессию перед перенаправлением пользователя в новое место. Обычно это делается, если пользователь спровоцировал ошибку валидации. После того как входные данные были переданы в сессию, вы можете легко получить их во время следующего запроса для повторного автозаполнения формы:

Другие типы ответов

Помощник response используется для генерации других типов экземпляров ответа. Когда помощник response вызывается без аргументов, возвращается реализация контракта IlluminateContractsRoutingResponseFactory . Этот контракт содержит несколько полезных методов для генерации ответов.

Ответы с HTML-шаблонами

Если вам нужен контроль над статусом и заголовками ответа, но также необходимо вернуть HTML-шаблон в качестве содержимого ответа, то вы должны использовать метод view :

Конечно, вы можете использовать глобальный помощник view , даже если вам не нужно передавать собственные код состояния или заголовки HTTP.

Ответы JSON

Метод json автоматически установит заголовок Content-Type в application/json , а также преобразует переданный массив в JSON с помощью функции json_encode PHP:

Если вы хотите создать ответ JSONP, вы можете использовать метод json в сочетании с методом withCallback :

Ответы для загрузки файлов

Метод download используется для генерации ответа, который заставляет браузер пользователя загружать файл по указанному пути. Метод download принимает имя файла в качестве второго аргумента метода, определяющий имя файла, которое видит пользователь, загружающий файл. Наконец, вы можете передать массив заголовков HTTP в качестве третьего аргумента метода:

Symfony HttpFoundation, управляющий загрузкой файлов, требует, чтобы имя загружаемого файла было в кодировке ASCII.

Потоковые загрузки

По желанию можно превратить строковый ответ переданной функции в загружаемый ответ без необходимости записывать результирующее содержимое на диск. В этом сценарии вы можете использовать метод streamDownload . Этот метод принимает в качестве аргументов замыкание, имя файла и необязательный массив заголовков:

Ответы, отображающие содержимое файлов

Метод file используется для отображения файла, такого как изображение или PDF, непосредственно в браузере пользователя вместо того, чтобы инициировать загрузку. Этот метод принимает путь к файлу в качестве первого аргумента и массив заголовков в качестве второго аргумента:

Макрокоманды ответа

Если вы хотите определить собственный ответ, который вы можете повторно использовать в различных маршрутах и контроллерах, то вы можете использовать метод macro фасада Response . Как правило, этот метод следует вызывать в методе boot одного из поставщиков служб вашего приложения, например, AppProvidersAppServiceProvider :

Метод macro принимает имя как свой первый аргумент и замыкание – как второй аргумент. Замыкание макрокоманды будет выполнено при вызове имени макрокоманды из реализации ResponseFactory или глобального помощника response :

Источник

HTTP Responses

Creating Responses

Strings & Arrays

All routes and controllers should return a response to be sent back to the user’s browser. Laravel provides several different ways to return responses. The most basic response is returning a string from a route or controller. The framework will automatically convert the string into a full HTTP response:

In addition to returning strings from your routes and controllers, you may also return arrays. The framework will automatically convert the array into a JSON response:

Note
Did you know you can also return Eloquent collections from your routes or controllers? They will automatically be converted to JSON. Give it a shot!

Response Objects

Typically, you won’t just be returning simple strings or arrays from your route actions. Instead, you will be returning full IlluminateHttpResponse instances or views.

Returning a full Response instance allows you to customize the response’s HTTP status code and headers. A Response instance inherits from the SymfonyComponentHttpFoundationResponse class, which provides a variety of methods for building HTTP responses:

Eloquent Models & Collections

You may also return Eloquent ORM models and collections directly from your routes and controllers. When you do, Laravel will automatically convert the models and collections to JSON responses while respecting the model’s hidden attributes:

Keep in mind that most response methods are chainable, allowing for the fluent construction of response instances. For example, you may use the header method to add a series of headers to the response before sending it back to the user:

Or, you may use the withHeaders method to specify an array of headers to be added to the response:

Cache Control Middleware

Laravel includes a cache.headers middleware, which may be used to quickly set the Cache-Control header for a group of routes. Directives should be provided using the «snake case» equivalent of the corresponding cache-control directive and should be separated by a semicolon. If etag is specified in the list of directives, an MD5 hash of the response content will automatically be set as the ETag identifier:

Attaching Cookies To Responses

You may attach a cookie to an outgoing IlluminateHttpResponse instance using the cookie method. You should pass the name, value, and the number of minutes the cookie should be considered valid to this method:

The cookie method also accepts a few more arguments which are used less frequently. Generally, these arguments have the same purpose and meaning as the arguments that would be given to PHP’s native setcookie method:

If you would like to ensure that a cookie is sent with the outgoing response but you do not yet have an instance of that response, you can use the Cookie facade to «queue» cookies for attachment to the response when it is sent. The queue method accepts the arguments needed to create a cookie instance. These cookies will be attached to the outgoing response before it is sent to the browser:

Generating Cookie Instances

If you would like to generate a SymfonyComponentHttpFoundationCookie instance that can be attached to a response instance at a later time, you may use the global cookie helper. This cookie will not be sent back to the client unless it is attached to a response instance:

Expiring Cookies Early

You may remove a cookie by expiring it via the withoutCookie method of an outgoing response:

If you do not yet have an instance of the outgoing response, you may use the Cookie facade’s expire method to expire a cookie:

Cookies & Encryption

By default, all cookies generated by Laravel are encrypted and signed so that they can’t be modified or read by the client. If you would like to disable encryption for a subset of cookies generated by your application, you may use the $except property of the AppHttpMiddlewareEncryptCookies middleware, which is located in the app/Http/Middleware directory:

Redirects

Redirect responses are instances of the IlluminateHttpRedirectResponse class, and contain the proper headers needed to redirect the user to another URL. There are several ways to generate a RedirectResponse instance. The simplest method is to use the global redirect helper:

Sometimes you may wish to redirect the user to their previous location, such as when a submitted form is invalid. You may do so by using the global back helper function. Since this feature utilizes the session, make sure the route calling the back function is using the web middleware group:

Redirecting To Named Routes

When you call the redirect helper with no parameters, an instance of IlluminateRoutingRedirector is returned, allowing you to call any method on the Redirector instance. For example, to generate a RedirectResponse to a named route, you may use the route method:

If your route has parameters, you may pass them as the second argument to the route method:

Populating Parameters Via Eloquent Models

If you are redirecting to a route with an «ID» parameter that is being populated from an Eloquent model, you may pass the model itself. The ID will be extracted automatically:

If you would like to customize the value that is placed in the route parameter, you can specify the column in the route parameter definition ( /profile/ ) or you can override the getRouteKey method on your Eloquent model:

Redirecting To Controller Actions

You may also generate redirects to controller actions. To do so, pass the controller and action name to the action method:

If your controller route requires parameters, you may pass them as the second argument to the action method:

Redirecting To External Domains

Sometimes you may need to redirect to a domain outside of your application. You may do so by calling the away method, which creates a RedirectResponse without any additional URL encoding, validation, or verification:

Redirecting With Flashed Session Data

Redirecting to a new URL and flashing data to the session are usually done at the same time. Typically, this is done after successfully performing an action when you flash a success message to the session. For convenience, you may create a RedirectResponse instance and flash data to the session in a single, fluent method chain:

After the user is redirected, you may display the flashed message from the session. For example, using Blade syntax:

Redirecting With Input

You may use the withInput method provided by the RedirectResponse instance to flash the current request’s input data to the session before redirecting the user to a new location. This is typically done if the user has encountered a validation error. Once the input has been flashed to the session, you may easily retrieve it during the next request to repopulate the form:

Other Response Types

The response helper may be used to generate other types of response instances. When the response helper is called without arguments, an implementation of the IlluminateContractsRoutingResponseFactory contract is returned. This contract provides several helpful methods for generating responses.

View Responses

If you need control over the response’s status and headers but also need to return a view as the response’s content, you should use the view method:

Of course, if you do not need to pass a custom HTTP status code or custom headers, you may use the global view helper function.

JSON Responses

The json method will automatically set the Content-Type header to application/json , as well as convert the given array to JSON using the json_encode PHP function:

If you would like to create a JSONP response, you may use the json method in combination with the withCallback method:

File Downloads

The download method may be used to generate a response that forces the user’s browser to download the file at the given path. The download method accepts a filename as the second argument to the method, which will determine the filename that is seen by the user downloading the file. Finally, you may pass an array of HTTP headers as the third argument to the method:

Warning
Symfony HttpFoundation, which manages file downloads, requires the file being downloaded to have an ASCII filename.

Streamed Downloads

Sometimes you may wish to turn the string response of a given operation into a downloadable response without having to write the contents of the operation to disk. You may use the streamDownload method in this scenario. This method accepts a callback, filename, and an optional array of headers as its arguments:

File Responses

The file method may be used to display a file, such as an image or PDF, directly in the user’s browser instead of initiating a download. This method accepts the path to the file as its first argument and an array of headers as its second argument:

Response Macros

If you would like to define a custom response that you can re-use in a variety of your routes and controllers, you may use the macro method on the Response facade. Typically, you should call this method from the boot method of one of your application’s service providers, such as the AppProvidersAppServiceProvider service provider:

The macro function accepts a name as its first argument and a closure as its second argument. The macro’s closure will be executed when calling the macro name from a ResponseFactory implementation or the response helper:

Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experience to be truly fulfilling. Laravel attempts to take the pain out of development by easing common tasks used in most web projects.

Источник

Version


HTTP Responses

  • Creating Responses

    • Attaching Headers To Responses
    • Attaching Cookies To Responses
    • Cookies & Encryption
  • Redirects

    • Redirecting To Named Routes
    • Redirecting To Controller Actions
    • Redirecting To External Domains
    • Redirecting With Flashed Session Data
  • Other Response Types

    • View Responses
    • JSON Responses
    • File Downloads
    • File Responses
  • Response Macros

Creating Responses

Strings & Arrays

All routes and controllers should return a response to be sent back to the user’s browser. Laravel provides several different ways to return responses. The most basic response is returning a string from a route or controller. The framework will automatically convert the string into a full HTTP response:

Route::get('/', function () {

return 'Hello World';

});

In addition to returning strings from your routes and controllers, you may also return arrays. The framework will automatically convert the array into a JSON response:

Route::get('/', function () {

return [1, 2, 3];

});

Note
Did you know you can also return Eloquent collections from your routes or controllers? They will automatically be converted to JSON. Give it a shot!

Response Objects

Typically, you won’t just be returning simple strings or arrays from your route actions. Instead, you will be returning full IlluminateHttpResponse instances or views.

Returning a full Response instance allows you to customize the response’s HTTP status code and headers. A Response instance inherits from the SymfonyComponentHttpFoundationResponse class, which provides a variety of methods for building HTTP responses:

Route::get('/home', function () {

return response('Hello World', 200)

->header('Content-Type', 'text/plain');

});

Eloquent Models & Collections

You may also return Eloquent ORM models and collections directly from your routes and controllers. When you do, Laravel will automatically convert the models and collections to JSON responses while respecting the model’s hidden attributes:

use AppModelsUser;

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

return $user;

});

Attaching Headers To Responses

Keep in mind that most response methods are chainable, allowing for the fluent construction of response instances. For example, you may use the header method to add a series of headers to the response before sending it back to the user:

return response($content)

->header('Content-Type', $type)

->header('X-Header-One', 'Header Value')

->header('X-Header-Two', 'Header Value');

Or, you may use the withHeaders method to specify an array of headers to be added to the response:

return response($content)

->withHeaders([

'Content-Type' => $type,

'X-Header-One' => 'Header Value',

'X-Header-Two' => 'Header Value',

]);

Cache Control Middleware

Laravel includes a cache.headers middleware, which may be used to quickly set the Cache-Control header for a group of routes. Directives should be provided using the «snake case» equivalent of the corresponding cache-control directive and should be separated by a semicolon. If etag is specified in the list of directives, an MD5 hash of the response content will automatically be set as the ETag identifier:

Route::middleware('cache.headers:public;max_age=2628000;etag')->group(function () {

Route::get('/privacy', function () {

// ...

});

Route::get('/terms', function () {

// ...

});

});

Attaching Cookies To Responses

You may attach a cookie to an outgoing IlluminateHttpResponse instance using the cookie method. You should pass the name, value, and the number of minutes the cookie should be considered valid to this method:

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

'name', 'value', $minutes

);

The cookie method also accepts a few more arguments which are used less frequently. Generally, these arguments have the same purpose and meaning as the arguments that would be given to PHP’s native setcookie method:

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

'name', 'value', $minutes, $path, $domain, $secure, $httpOnly

);

If you would like to ensure that a cookie is sent with the outgoing response but you do not yet have an instance of that response, you can use the Cookie facade to «queue» cookies for attachment to the response when it is sent. The queue method accepts the arguments needed to create a cookie instance. These cookies will be attached to the outgoing response before it is sent to the browser:

use IlluminateSupportFacadesCookie;

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

Generating Cookie Instances

If you would like to generate a SymfonyComponentHttpFoundationCookie instance that can be attached to a response instance at a later time, you may use the global cookie helper. This cookie will not be sent back to the client unless it is attached to a response instance:

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

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

Expiring Cookies Early

You may remove a cookie by expiring it via the withoutCookie method of an outgoing response:

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

If you do not yet have an instance of the outgoing response, you may use the Cookie facade’s expire method to expire a cookie:

Cookie::expire('name');

Cookies & Encryption

By default, all cookies generated by Laravel are encrypted and signed so that they can’t be modified or read by the client. If you would like to disable encryption for a subset of cookies generated by your application, you may use the $except property of the AppHttpMiddlewareEncryptCookies middleware, which is located in the app/Http/Middleware directory:

/**

* The names of the cookies that should not be encrypted.

*

* @var array

*/

protected $except = [

'cookie_name',

];

Redirects

Redirect responses are instances of the IlluminateHttpRedirectResponse class, and contain the proper headers needed to redirect the user to another URL. There are several ways to generate a RedirectResponse instance. The simplest method is to use the global redirect helper:

Route::get('/dashboard', function () {

return redirect('home/dashboard');

});

Sometimes you may wish to redirect the user to their previous location, such as when a submitted form is invalid. You may do so by using the global back helper function. Since this feature utilizes the session, make sure the route calling the back function is using the web middleware group:

Route::post('/user/profile', function () {

// Validate the request...

return back()->withInput();

});

Redirecting To Named Routes

When you call the redirect helper with no parameters, an instance of IlluminateRoutingRedirector is returned, allowing you to call any method on the Redirector instance. For example, to generate a RedirectResponse to a named route, you may use the route method:

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

If your route has parameters, you may pass them as the second argument to the route method:

// For a route with the following URI: /profile/{id}

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

Populating Parameters Via Eloquent Models

If you are redirecting to a route with an «ID» parameter that is being populated from an Eloquent model, you may pass the model itself. The ID will be extracted automatically:

// For a route with the following URI: /profile/{id}

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

If you would like to customize the value that is placed in the route parameter, you can specify the column in the route parameter definition (/profile/{id:slug}) or you can override the getRouteKey method on your Eloquent model:

/**

* Get the value of the model's route key.

*

* @return mixed

*/

public function getRouteKey()

{

return $this->slug;

}

Redirecting To Controller Actions

You may also generate redirects to controller actions. To do so, pass the controller and action name to the action method:

use AppHttpControllersUserController;

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

If your controller route requires parameters, you may pass them as the second argument to the action method:

return redirect()->action(

[UserController::class, 'profile'], ['id' => 1]

);

Redirecting To External Domains

Sometimes you may need to redirect to a domain outside of your application. You may do so by calling the away method, which creates a RedirectResponse without any additional URL encoding, validation, or verification:

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

Redirecting With Flashed Session Data

Redirecting to a new URL and flashing data to the session are usually done at the same time. Typically, this is done after successfully performing an action when you flash a success message to the session. For convenience, you may create a RedirectResponse instance and flash data to the session in a single, fluent method chain:

Route::post('/user/profile', function () {

// ...

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

});

After the user is redirected, you may display the flashed message from the session. For example, using Blade syntax:

@if (session('status'))

<div class="alert alert-success">

{{ session('status') }}

</div>

@endif

Redirecting With Input

You may use the withInput method provided by the RedirectResponse instance to flash the current request’s input data to the session before redirecting the user to a new location. This is typically done if the user has encountered a validation error. Once the input has been flashed to the session, you may easily retrieve it during the next request to repopulate the form:

return back()->withInput();

Other Response Types

The response helper may be used to generate other types of response instances. When the response helper is called without arguments, an implementation of the IlluminateContractsRoutingResponseFactory contract is returned. This contract provides several helpful methods for generating responses.

View Responses

If you need control over the response’s status and headers but also need to return a view as the response’s content, you should use the view method:

return response()

->view('hello', $data, 200)

->header('Content-Type', $type);

Of course, if you do not need to pass a custom HTTP status code or custom headers, you may use the global view helper function.

JSON Responses

The json method will automatically set the Content-Type header to application/json, as well as convert the given array to JSON using the json_encode PHP function:

return response()->json([

'name' => 'Abigail',

'state' => 'CA',

]);

If you would like to create a JSONP response, you may use the json method in combination with the withCallback method:

return response()

->json(['name' => 'Abigail', 'state' => 'CA'])

->withCallback($request->input('callback'));

File Downloads

The download method may be used to generate a response that forces the user’s browser to download the file at the given path. The download method accepts a filename as the second argument to the method, which will determine the filename that is seen by the user downloading the file. Finally, you may pass an array of HTTP headers as the third argument to the method:

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

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

Warning
Symfony HttpFoundation, which manages file downloads, requires the file being downloaded to have an ASCII filename.

Streamed Downloads

Sometimes you may wish to turn the string response of a given operation into a downloadable response without having to write the contents of the operation to disk. You may use the streamDownload method in this scenario. This method accepts a callback, filename, and an optional array of headers as its arguments:

use AppServicesGitHub;

return response()->streamDownload(function () {

echo GitHub::api('repo')

->contents()

->readme('laravel', 'laravel')['contents'];

}, 'laravel-readme.md');

File Responses

The file method may be used to display a file, such as an image or PDF, directly in the user’s browser instead of initiating a download. This method accepts the path to the file as its first argument and an array of headers as its second argument:

return response()->file($pathToFile);

return response()->file($pathToFile, $headers);

Response Macros

If you would like to define a custom response that you can re-use in a variety of your routes and controllers, you may use the macro method on the Response facade. Typically, you should call this method from the boot method of one of your application’s service providers, such as the AppProvidersAppServiceProvider service provider:

<?php

namespace AppProviders;

use IlluminateSupportFacadesResponse;

use IlluminateSupportServiceProvider;

class AppServiceProvider extends ServiceProvider

{

/**

* Bootstrap any application services.

*

* @return void

*/

public function boot()

{

Response::macro('caps', function ($value) {

return Response::make(strtoupper($value));

});

}

}

The macro function accepts a name as its first argument and a closure as its second argument. The macro’s closure will be executed when calling the macro name from a ResponseFactory implementation or the response helper:

return response()->caps('foo');

  • Создание ответов

    • Добавление заголовков к ответам
    • Добавление файлов Cookies к ответам
    • Файлы Cookies и шифрование
  • Перенаправления

    • Перенаправление на именованные маршруты
    • Перенаправление к действиям контроллера
    • Перенаправление на внешние домены
    • Перенаправление с кратковременным сохранением данных в сессии
  • Другие типы ответов

    • Ответы с HTML-шаблонами
    • Ответы JSON
    • Ответы для загрузки файлов
    • Ответы, отображающие содержимое файлов
  • Макрокоманды ответа

Создание ответов

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

Все маршруты и контроллеры должны возвращать ответ, который будет отправлен обратно в браузер пользователя. Laravel предлагает несколько разных способов вернуть ответы. Самый простой ответ – это возврат строки из маршрута или контроллера. Фреймворк автоматически преобразует строку в полный HTTP-ответ:

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

Помимо возврата строк из ваших маршрутов и контроллеров, вы также можете возвращать массивы. Фреймворк автоматически преобразует массив в ответ JSON:

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

Знаете ли вы, что можете возвращать коллекции Eloquent из ваших маршрутов или контроллеров? Они будут автоматически преобразованы в JSON.

Объекты ответа

Как правило, вы не просто будете возвращать строки или массивы из действий маршрута. Вместо этого вы вернете полные экземпляры IlluminateHttpResponse или шаблоны.

Возврат полного экземпляра Response позволяет вам настроить код состояния и заголовки HTTP ответа. Экземпляр Response наследуется от класса SymfonyComponentHttpFoundationResponse, который содержит множество методов для построения ответов HTTP:

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

Модели и коллекции Eloquent

По желанию можно вернуть модели и коллекции Eloquent ORM прямо из ваших маршрутов и контроллеров. Когда вы это сделаете, Laravel автоматически преобразует модели и коллекции в ответы JSON, учитывая скрытие атрибутов модели:

use AppModelsUser;

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

Добавление заголовков к ответам

Имейте в виду, что большинство методов ответа можно объединять в цепочку вызовов для гибкого создания экземпляров ответа. Например, вы можете использовать метод header для добавления серии заголовков к ответу перед его отправкой обратно пользователю:

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

Или вы можете использовать метод withHeaders, чтобы указать массив заголовков, которые будут добавлены к ответу:

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

Посредник управления кешем

Laravel содержит посредник cache.headers, используемый для быстрой установки заголовка Cache-Control для группы маршрутов. Директивы должны быть предоставлены с использованием эквивалента «snake case» соответствующей директивы управления кешем и должны быть разделены точкой с запятой. Если в списке директив указан etag, то MD5-хеш содержимого ответа будет автоматически установлен как идентификатор ETag:

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

    Route::get('/terms', function () {
        // ...
    });
});

Добавление файлов Cookies к ответам

Вы можете добавить Cookies к исходящему экземпляру IlluminateHttpResponse, используя метод cookie. Вы должны передать этому методу имя, значение и количество минут, в течение которых куки должен считаться действительным:

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

Метод cookie также принимает еще несколько аргументов, которые используются реже. Как правило, эти аргументы имеют то же назначение и значение, что и аргументы, передаваемые встроенному в PHP методу setcookie method:

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

Если вы хотите, чтобы куки отправлялся вместе с исходящим ответом, но у вас еще нет экземпляра этого ответа, вы можете использовать фасад Cookie, чтобы «поставить в очередь» файлы Cookies для добавления их к ответу при его отправке. Метод queue принимает аргументы, необходимые для создания экземпляра Cookie. Эти файлы Cookies будут добавлены к исходящему ответу перед его отправкой в браузер:

use IlluminateSupportFacadesCookie;

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

Создание экземпляров Cookie

Если вы хотите сгенерировать экземпляр SymfonyComponentHttpFoundationCookie, который может быть добавлен к экземпляру ответа позже, вы можете использовать глобальный помощник cookie. Этот файл Cookies не будет отправлен обратно клиенту, если он не прикреплен к экземпляру ответа:

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

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

Досрочное окончание срока действия файлов Cookies

Вы можете удалить куки, обнулив срок его действия с помощью метода withoutCookie исходящего ответа:

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

Если у вас еще нет экземпляра исходящего ответа, вы можете использовать метод expire фасада Cookie для обнуления срока действия кук:

Cookie::expire('name');

Файлы Cookies и шифрование

По умолчанию все файлы Cookies, генерируемые Laravel, зашифрованы и подписаны, поэтому клиент не может их изменить или прочитать. Если вы хотите отключить шифрование для некоторого подмножества файлов Cookies, создаваемых вашим приложением, вы можете использовать свойство $except посредника AppHttpMiddlewareEncryptCookies, находящегося в каталоге app/Http/Middleware:

/**
 * Имена файлов Cookies, которые не должны быть зашифрованы.
 *
 * @var array
 */
protected $except = [
    'cookie_name',
];

Перенаправления

Ответы с перенаправлением являются экземплярами класса IlluminateHttpRedirectResponse и содержат корректные заголовки, необходимые для перенаправления пользователя на другой URL. Есть несколько способов сгенерировать экземпляр RedirectResponse. Самый простой способ – использовать глобальный помощник redirect:

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

По желанию можно перенаправить пользователя в его предыдущее местоположение, например, когда отправленная форма является недействительной. Вы можете сделать это с помощью глобального помощника back. Поскольку эта функция использует сессии, убедитесь, что маршрут, вызывающий функцию back, использует группу посредников web:

Route::post('/user/profile', function () {
    // Валидация запроса ...

    return back()->withInput();
});

Перенаправление на именованные маршруты

Когда вы вызываете помощник redirect без параметров, возвращается экземпляр IlluminateRoutingRedirector, что позволяет вам вызывать любой метод экземпляра Redirector. Например, чтобы сгенерировать RedirectResponse на именованный маршрут, вы можете использовать метод route:

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

Если ваш маршрут имеет параметры, вы можете передать их в качестве второго аргумента методу route:

// Для маршрута со следующим URI: /profile/{id}

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

Заполнение параметров с моделей Eloquent

Если вы перенаправляете на маршрут с параметром ID, который извлекается из модели Eloquent, то вы можете просто передать саму модель. ID будет извлечен автоматически:

// Для маршрута со следующим URI: /profile/{id}

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

Если вы хотите настроить значение, которое соответствует параметру маршрута, то вы можете указать столбец при определении параметра маршрута (/profile/{id:slug}) или переопределить метод getRouteKey в вашей модели Eloquent:

/**
 * Получить значение ключа маршрута модели.
 *
 * @return mixed
 */
public function getRouteKey()
{
    return $this->slug;
}

Перенаправление к действиям контроллера

Вы также можете генерировать перенаправления на действия контроллера. Для этого передайте имя контроллера и действия методу action:

use AppHttpControllersUserController;

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

Если ваш маршрут контроллера требует параметров, вы можете передать их в качестве второго аргумента методу action:

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

Перенаправление на внешние домены

Иногда может потребоваться перенаправление на домен за пределами вашего приложения. Вы можете сделать это, вызвав метод away, который создает RedirectResponse без какой-либо дополнительной кодировки URL, валидации или проверки:

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

Перенаправление с кратковременным сохранением данных в сессии

Перенаправление на новый URL-адрес и краткосрочная запись данных в сессию обычно выполняются одновременно. Обычно это делается после успешного выполнения действия, когда вы отправляете сообщение об успешном завершении в сессию. Для удобства вы можете создать экземпляр RedirectResponse и передать данные в сессию в единой текучей цепочке методов:

Route::post('/user/profile', function () {
    // ...

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

После перенаправления пользователя, вы можете отобразить сохраненное из сессии сообщение. Например, используя синтаксис Blade:

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

Перенаправление с кратковременным сохранением входных данных

Вы можете использовать метод withInput экземпляра RedirectResponse, для передачи входных данных текущего запроса в сессию перед перенаправлением пользователя в новое место. Обычно это делается, если пользователь спровоцировал ошибку валидации. После того как входные данные были переданы в сессию, вы можете легко получить их во время следующего запроса для повторного автозаполнения формы:

return back()->withInput();

Другие типы ответов

Помощник response используется для генерации других типов экземпляров ответа. Когда помощник response вызывается без аргументов, возвращается реализация контракта IlluminateContractsRoutingResponseFactory. Этот контракт содержит несколько полезных методов для генерации ответов.

Ответы с HTML-шаблонами

Если вам нужен контроль над статусом и заголовками ответа, но также необходимо вернуть HTML-шаблон в качестве содержимого ответа, то вы должны использовать метод view:

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

Конечно, вы можете использовать глобальный помощник view, даже если вам не нужно передавать собственные код состояния или заголовки HTTP.

Ответы JSON

Метод json автоматически установит заголовок Content-Type в application/json, а также преобразует переданный массив в JSON с помощью функции json_encode PHP:

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

Если вы хотите создать ответ JSONP, вы можете использовать метод json в сочетании с методом withCallback:

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

Ответы для загрузки файлов

Метод download используется для генерации ответа, который заставляет браузер пользователя загружать файл по указанному пути. Метод download принимает имя файла в качестве второго аргумента метода, определяющий имя файла, которое видит пользователь, загружающий файл. Наконец, вы можете передать массив заголовков HTTP в качестве третьего аргумента метода:

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

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

Symfony HttpFoundation, управляющий загрузкой файлов, требует, чтобы имя загружаемого файла было в кодировке ASCII.

Потоковые загрузки

По желанию можно превратить строковый ответ переданной функции в загружаемый ответ без необходимости записывать результирующее содержимое на диск. В этом сценарии вы можете использовать метод streamDownload. Этот метод принимает в качестве аргументов замыкание, имя файла и необязательный массив заголовков:

use AppServicesGitHub;

return response()->streamDownload(function () {
    echo GitHub::api('repo')
                ->contents()
                ->readme('laravel', 'laravel')['contents'];
}, 'laravel-readme');

Ответы, отображающие содержимое файлов

Метод file используется для отображения файла, такого как изображение или PDF, непосредственно в браузере пользователя вместо того, чтобы инициировать загрузку. Этот метод принимает путь к файлу в качестве первого аргумента и массив заголовков в качестве второго аргумента:

return response()->file($pathToFile);

return response()->file($pathToFile, $headers);

Макрокоманды ответа

Если вы хотите определить собственный ответ, который вы можете повторно использовать в различных маршрутах и контроллерах, то вы можете использовать метод macro фасада Response. Как правило, этот метод следует вызывать в методе boot одного из поставщиков служб вашего приложения, например, AppProvidersAppServiceProvider:

<?php

namespace AppProviders;

use IlluminateSupportFacadesResponse;
use IlluminateSupportServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Загрузка любых служб приложения.
     *
     * @return void
     */
    public function boot()
    {
        Response::macro('caps', function ($value) {
            return Response::make(strtoupper($value));
        });
    }
}

Метод macro принимает имя как свой первый аргумент и замыкание – как второй аргумент. Замыкание макрокоманды будет выполнено при вызове имени макрокоманды из реализации ResponseFactory или глобального помощника response:

return response()->caps('foo');

Версия


HTTP Responses

  • Creating Responses

    • Attaching Headers To Responses
    • Attaching Cookies To Responses
    • Cookies & Encryption
  • Redirects

    • Redirecting To Named Routes
    • Redirecting To Controller Actions
    • Redirecting To External Domains
    • Redirecting With Flashed Session Data
  • Other Response Types

    • View Responses
    • JSON Responses
    • File Downloads
    • File Responses
  • Response Macros

Creating Responses

Strings & Arrays

All routes and controllers should return a response to be sent back to the user’s browser. Laravel provides several different ways to return responses. The most basic response is returning a string from a route or controller. The framework will automatically convert the string into a full HTTP response:

Route::get('/', function () {

return 'Hello World';

});

In addition to returning strings from your routes and controllers, you may also return arrays. The framework will automatically convert the array into a JSON response:

Route::get('/', function () {

return [1, 2, 3];

});

{tip} Did you know you can also return Eloquent collections from your routes or controllers? They will automatically be converted to JSON. Give it a shot!

Response Objects

Typically, you won’t just be returning simple strings or arrays from your route actions. Instead, you will be returning full IlluminateHttpResponse instances or views.

Returning a full Response instance allows you to customize the response’s HTTP status code and headers. A Response instance inherits from the SymfonyComponentHttpFoundationResponse class, which provides a variety of methods for building HTTP responses:

Route::get('/home', function () {

return response('Hello World', 200)

->header('Content-Type', 'text/plain');

});

Eloquent Models & Collections

You may also return Eloquent ORM models and collections directly from your routes and controllers. When you do, Laravel will automatically convert the models and collections to JSON responses while respecting the model’s hidden attributes:

use AppModelsUser;

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

return $user;

});

Attaching Headers To Responses

Keep in mind that most response methods are chainable, allowing for the fluent construction of response instances. For example, you may use the header method to add a series of headers to the response before sending it back to the user:

return response($content)

->header('Content-Type', $type)

->header('X-Header-One', 'Header Value')

->header('X-Header-Two', 'Header Value');

Or, you may use the withHeaders method to specify an array of headers to be added to the response:

return response($content)

->withHeaders([

'Content-Type' => $type,

'X-Header-One' => 'Header Value',

'X-Header-Two' => 'Header Value',

]);

Cache Control Middleware

Laravel includes a cache.headers middleware, which may be used to quickly set the Cache-Control header for a group of routes. Directives should be provided using the «snake case» equivalent of the corresponding cache-control directive and should be separated by a semicolon. If etag is specified in the list of directives, an MD5 hash of the response content will automatically be set as the ETag identifier:

Route::middleware('cache.headers:public;max_age=2628000;etag')->group(function () {

Route::get('/privacy', function () {

// ...

});

Route::get('/terms', function () {

// ...

});

});

Attaching Cookies To Responses

You may attach a cookie to an outgoing IlluminateHttpResponse instance using the cookie method. You should pass the name, value, and the number of minutes the cookie should be considered valid to this method:

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

'name', 'value', $minutes

);

The cookie method also accepts a few more arguments which are used less frequently. Generally, these arguments have the same purpose and meaning as the arguments that would be given to PHP’s native setcookie method:

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

'name', 'value', $minutes, $path, $domain, $secure, $httpOnly

);

If you would like to ensure that a cookie is sent with the outgoing response but you do not yet have an instance of that response, you can use the Cookie facade to «queue» cookies for attachment to the response when it is sent. The queue method accepts the arguments needed to create a cookie instance. These cookies will be attached to the outgoing response before it is sent to the browser:

use IlluminateSupportFacadesCookie;

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

Generating Cookie Instances

If you would like to generate a SymfonyComponentHttpFoundationCookie instance that can be attached to a response instance at a later time, you may use the global cookie helper. This cookie will not be sent back to the client unless it is attached to a response instance:

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

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

Expiring Cookies Early

You may remove a cookie by expiring it via the withoutCookie method of an outgoing response:

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

If you do not yet have an instance of the outgoing response, you may use the Cookie facade’s expire method to expire a cookie:

Cookie::expire('name');

Cookies & Encryption

By default, all cookies generated by Laravel are encrypted and signed so that they can’t be modified or read by the client. If you would like to disable encryption for a subset of cookies generated by your application, you may use the $except property of the AppHttpMiddlewareEncryptCookies middleware, which is located in the app/Http/Middleware directory:

/**

* The names of the cookies that should not be encrypted.

*

* @var array

*/

protected $except = [

'cookie_name',

];

Redirects

Redirect responses are instances of the IlluminateHttpRedirectResponse class, and contain the proper headers needed to redirect the user to another URL. There are several ways to generate a RedirectResponse instance. The simplest method is to use the global redirect helper:

Route::get('/dashboard', function () {

return redirect('home/dashboard');

});

Sometimes you may wish to redirect the user to their previous location, such as when a submitted form is invalid. You may do so by using the global back helper function. Since this feature utilizes the session, make sure the route calling the back function is using the web middleware group:

Route::post('/user/profile', function () {

// Validate the request...

return back()->withInput();

});

Redirecting To Named Routes

When you call the redirect helper with no parameters, an instance of IlluminateRoutingRedirector is returned, allowing you to call any method on the Redirector instance. For example, to generate a RedirectResponse to a named route, you may use the route method:

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

If your route has parameters, you may pass them as the second argument to the route method:

// For a route with the following URI: /profile/{id}

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

Populating Parameters Via Eloquent Models

If you are redirecting to a route with an «ID» parameter that is being populated from an Eloquent model, you may pass the model itself. The ID will be extracted automatically:

// For a route with the following URI: /profile/{id}

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

If you would like to customize the value that is placed in the route parameter, you can specify the column in the route parameter definition (/profile/{id:slug}) or you can override the getRouteKey method on your Eloquent model:

/**

* Get the value of the model's route key.

*

* @return mixed

*/

public function getRouteKey()

{

return $this->slug;

}

Redirecting To Controller Actions

You may also generate redirects to controller actions. To do so, pass the controller and action name to the action method:

use AppHttpControllersUserController;

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

If your controller route requires parameters, you may pass them as the second argument to the action method:

return redirect()->action(

[UserController::class, 'profile'], ['id' => 1]

);

Redirecting To External Domains

Sometimes you may need to redirect to a domain outside of your application. You may do so by calling the away method, which creates a RedirectResponse without any additional URL encoding, validation, or verification:

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

Redirecting With Flashed Session Data

Redirecting to a new URL and flashing data to the session are usually done at the same time. Typically, this is done after successfully performing an action when you flash a success message to the session. For convenience, you may create a RedirectResponse instance and flash data to the session in a single, fluent method chain:

Route::post('/user/profile', function () {

// ...

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

});

After the user is redirected, you may display the flashed message from the session. For example, using Blade syntax:

@if (session('status'))

<div class="alert alert-success">

{{ session('status') }}

</div>

@endif

Redirecting With Input

You may use the withInput method provided by the RedirectResponse instance to flash the current request’s input data to the session before redirecting the user to a new location. This is typically done if the user has encountered a validation error. Once the input has been flashed to the session, you may easily retrieve it during the next request to repopulate the form:

return back()->withInput();

Other Response Types

The response helper may be used to generate other types of response instances. When the response helper is called without arguments, an implementation of the IlluminateContractsRoutingResponseFactory contract is returned. This contract provides several helpful methods for generating responses.

View Responses

If you need control over the response’s status and headers but also need to return a view as the response’s content, you should use the view method:

return response()

->view('hello', $data, 200)

->header('Content-Type', $type);

Of course, if you do not need to pass a custom HTTP status code or custom headers, you may use the global view helper function.

JSON Responses

The json method will automatically set the Content-Type header to application/json, as well as convert the given array to JSON using the json_encode PHP function:

return response()->json([

'name' => 'Abigail',

'state' => 'CA',

]);

If you would like to create a JSONP response, you may use the json method in combination with the withCallback method:

return response()

->json(['name' => 'Abigail', 'state' => 'CA'])

->withCallback($request->input('callback'));

File Downloads

The download method may be used to generate a response that forces the user’s browser to download the file at the given path. The download method accepts a filename as the second argument to the method, which will determine the filename that is seen by the user downloading the file. Finally, you may pass an array of HTTP headers as the third argument to the method:

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

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

{note} Symfony HttpFoundation, which manages file downloads, requires the file being downloaded to have an ASCII filename.

Streamed Downloads

Sometimes you may wish to turn the string response of a given operation into a downloadable response without having to write the contents of the operation to disk. You may use the streamDownload method in this scenario. This method accepts a callback, filename, and an optional array of headers as its arguments:

use AppServicesGitHub;

return response()->streamDownload(function () {

echo GitHub::api('repo')

->contents()

->readme('laravel', 'laravel')['contents'];

}, 'laravel-readme.md');

File Responses

The file method may be used to display a file, such as an image or PDF, directly in the user’s browser instead of initiating a download. This method accepts the path to the file as its first argument and an array of headers as its second argument:

return response()->file($pathToFile);

return response()->file($pathToFile, $headers);

Response Macros

If you would like to define a custom response that you can re-use in a variety of your routes and controllers, you may use the macro method on the Response facade. Typically, you should call this method from the boot method of one of your application’s service providers, such as the AppProvidersAppServiceProvider service provider:

<?php

namespace AppProviders;

use IlluminateSupportFacadesResponse;

use IlluminateSupportServiceProvider;

class AppServiceProvider extends ServiceProvider

{

/**

* Bootstrap any application services.

*

* @return void

*/

public function boot()

{

Response::macro('caps', function ($value) {

return Response::make(strtoupper($value));

});

}

}

The macro function accepts a name as its first argument and a closure as its second argument. The macro’s closure will be executed when calling the macro name from a ResponseFactory implementation or the response helper:

return response()->caps('foo');

Понравилась статья? Поделить с друзьями:

Читайте также:

  • La noire ошибка отсутствует dll переустановите social club на пиратке
  • La noire ошибка gsrld dll
  • L9п старлайн ошибка а91 что означает
  • Laravel request validation return error
  • L9p ошибка старлайн а91

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии