laravel redirect with message
Laravel redirect back with () message
попытка перенаправления на предыдущую страницу с сообщением, когда есть фатальная ошибка.
в представлении пытается получить доступ к msg с
12 ответов:
и внутри вашего взгляда назовите это
контроллер
в Laravel 5.4 для меня работало следующее:
Я думаю, теперь это должно работать, это делает для меня.
просто установите флэш-сообщение и перенаправить обратно с вашего контроллера функции.
и затем вы можете получить сообщение в виде файла Блейда.
я перестал писать эту себя за то, что Laravel в пользу пакет Laracasts, который обрабатывает все это для вас. Он очень прост в использовании и сохраняет ваш код в чистоте. Есть даже laracast это охватывает, как его использовать. Все что вам нужно сделать:
вытащить в пакет через Composer.
включите поставщика услуг в app / config / app.РНР.
добавить псевдоним фасада к этому же файлу на странице снизу:
вытяните HTML в представление:
есть кнопка закрытия справа от сообщения. Это зависит от jQuery, поэтому убедитесь, что он добавлен перед загрузкой.
изменения:
если вы не используете bootstrap или хотите пропустить включение флэш-сообщения и написать код самостоятельно:
Если вам нужно изменить частичные сделать:
два вида пакетов теперь будут расположены в каталоге’ app/views/packages/laracasts/flash/’.
HTTP Redirects
Creating Redirects
Redirect responses are instances of the Illuminate\Http\RedirectResponse 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 or has all of the session middleware applied:
Redirecting To Named Routes
When you call the redirect helper with no parameters, an instance of Illuminate\Routing\Redirector 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 should 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 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:
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. Once the input has been flashed to the session, you may easily retrieve it during the next request:
After the user is redirected, you may display the flashed message from the session. For example, using Blade syntax:
Laravel Framework Russian Community
Prologue
Getting Started
Architecture Concepts
The Basics
Frontend
Security
Digging Deeper
Database
Eloquent ORM
Testing
Official Packages
HTTP Redirects
Creating Redirects
Redirect responses are instances of the Illuminate\Http\RedirectResponse 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 or has all of the session middleware applied:
Redirecting To Named Routes
When you call the redirect helper with no parameters, an instance of Illuminate\Routing\Redirector 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 should 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. Remember, you do not need to specify the full namespace to the controller since Laravel’s RouteServiceProvider will automatically set the base controller namespace:
If your controller route requires parameters, you may pass them as the second argument to the action method:
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:
Все о WEB программировании
WEB программирование от А до Я
Заказать сайт:
Социальные сети:
Партнеры:
Redirect (перенаправление) в Laravel 5
Доброго времени суток. В данной статье я опишу такую замечательную функцию Laravel – redirect. Мы рассмотрим перенаправление пользователей на другие страницы или действие (action) с данными, так и без данных. Ну что, приступим…
Очень часто нам приходится перенаправлять пользователя на другую страницу или действие ( action), например при неверно введенных данных в форме вернуть пользователя обратно.
Простое перенаправление
Например нам надо перенаправить пользователя на страницу page, http://website.loc/page
Или перенаправим пользователя на страницу авторизации http://website.loc/auth/login
Перенаправление на предыдущую страницу
Например, пользователь ввел неверные данные в форму и отправил форму. После проверки мы выявили ошибки и нам необходимо перенаправить пользователя обратно на эту форму:
Перенаправление с данными
Как в примере приведенном выше, при неверно введенных данных мы хотим перенаправить пользователя обратно на форму, но при этом вывести сообщение «Неверно введены данные»
А в самом представлении (view) формы поймать это сообщение при помощи сессии:
Мы можем применять несколько методов with(), например:
Но удобней в этом случае использовать массив:
Если мы перенаправляем пользователя обратно на форму, то мы можем перенаправить со старыми значениями для этого используем метод withInput()
А данные в форме мы можем получить данные используя функцию old(‘key’).
Перенаправление на именованный роут.
Например у нас есть именованный роут:
Мы хотим перенаправить пользователя на данное действие не по ссылке, а по имени данного роута.
Данный способ очень удобен. Если в дальнейшем мы захотим изменить структуру URL, то нам необходимо только подкорректировать файл route.php.
Если роут содержит параметр или группу параметров:
То мы можем использовать редирект на именованный роут:
Редирект на контролер и действие
Иногда необходимо перенаправить пользователя на конкретный метод контролера не используя URL. Для этого мы можем использовать полный путь к методу:
Также мы можем передать параметры, просто добавив их в массив:
Laravel Redirect Back with() Message
Я пытаюсь перенаправить на предыдущую страницу с сообщением, когда есть фатальная ошибка.
По мнению попытке открыть сообщение с
Но ничего не получается, неужели я делаю что-то не так?
и внутри вашего взгляда назовите это
Альтернативным подходом было бы
У вас есть ошибка (орфографическая ошибка):
Я думаю, что теперь это должно сработать, это делает для меня.
Я перестал писать это сам для laravel в пользу пакета Laracasts, который обрабатывает все это для вас. Он действительно прост в использовании и сохраняет ваш код чистым. Существует даже laracast, который описывает, как его использовать. Все, что вам нужно сделать:
Втяните пакет через Composer.
Включают услугодателя в течение app/config/app.php.
Добавьте псевдоним фасада в этот же файл внизу страницы:
Справа от сообщения находится кнопка закрытия. Это зависит от jQuery, поэтому убедитесь, что он добавлен перед загрузкой.
необязательные изменения:
Если вы не используете bootstrap или хотите пропустить включение флэш-сообщения и написать код самостоятельно:
Если вам нужно изменить партиалы сделайте это:
Два представления пакета теперь будет располагаться в приложение/просмотров/пакеты каталог/laracasts/вспышки/’.