Redirect to route not redirecting in laravel - php

I've been using Laravel-5.8.35. I was invoking a GET request through a form. On my route, I redirected the form action to the same controller where the form was submitted but redirected through a different route, as,
$router->get('/merchant/sd-refund', 'Reports\ReportController#refundSecurityDeposit');
And, in my refundSecurityDeposit method, I called my SohojSdRefundService service,
public function refundSecurityDeposit(Request $request)
{
// $userId, $reason, $sdAmount was fetched from the $request instance
$this->execRefundRequest($userId, $reason, $sdAmount);
}
public function execRefundRequest($userId, $reason, $sdAmount)
{
// here the API service request data was handled,
// and stored in $data instance
return SohojSdRefundService::callSdRefundApi($data);
}
While my SohojSdRefundService service was done handling, I wanted to redirect the route to another route, as,
class SohojSdRefundService
{
public function __construct()
{
}
public static function callSdRefundApi($requestData)
{
// call to other methods inside the class to handle the API response,
// and then return to the same route which isn't working
return redirect('/admin/merchant/list');
}
}
Respectively, instead of redirecting to that route, the page happens to be still on the /merchant/sd-refund?... where the form was submitted initially. I redirected another service like this, which is working fine though. Could anyone suggest what I could be implementing wrong here? TIA.

You need to return a result in refundSecurityDeposit fucntion
public function refundSecurityDeposit(Request $request)
{
return $this->execRefundRequest($userId, $reason, $sdAmount);
}

Related

The GET method is not supported for this route. Supported methods: POST on Flutterwave implementation with laravel

I am implementing Flutterwave implementation as found on Medium but I am getting the error:
The GET method is not supported for this route. Supported methods: POST.
http://localhost:8000/rave/callback?resp=%7B%22name%22%3A%22opop%22%2C%22data%22%3A%7B%22data%22%3A%7B%22responsecode%22%3A%2200%22%2C%22responsetoken%22%3Anull%2C%22responsemessage%22%3A%22successful%22%7D%2C%22tx%22%3A%7B%22id%22%3A2424493%2C%22txRef%22%3A%22rave_611fc5fe12df9%22%2C%22orderRef%22%3A%22URF_1629472286526_3670035%22%2C%22flwRef%22%3A%22FLW-MOCK-44b7ecdb3a2183c971db03d669dc1554%22%2C%22redirectUrl%22%3A%22http%3A%2F%2Flocalhost%3A8000%2Frave%2Fcallback%22%2C%22device_fingerprint%22%3A%22888b449800a5003eaf1eeea02d5d52db%22%2C%22settlement_token%22%3_
I am implementing Post routes as shown in:
Route::post('/pay', 'RaveController#initialize')->name('pay');
Route::post('/rave/callback', 'RaveController#callback')->name('callback');
And on my controller, I've got:
public function initialize() {
//This initializes payment and redirects to the payment gateway
//The initialize method takes the parameter of the redirect URL
Rave::initialize(route('callback'));
}
/**
* Obtain Rave callback information
* #return void
*/
public function callback() {
$data = Rave::verifyTransaction(request()->txref);
dd($data); // view the data response
if ($data->status == 'success') {
//do something to your database
} else {
//return invalid payment
}
}
Please can anyone help me solve this problem? Especially since changing the route to get returns null. Thanks a whole lot!
that's because of you are calling the route again here that is mean you will go to this direction with get method
public function initialize(){
Rave::initialize(route('callback'));
}
the best solution to you you have to call this function without routing it as following
public function initialize(Request $request){
//here now you will not routing with get you will call the function inside it
Rave::initialize($this->callback($request->all()));
}
/**
* Obtain Rave callback information
* #return void
*/public function callback($request){
$data = Rave::verifyTransaction($request->txref);
dd($data); // view the data response
if ($data->status == 'success') {
//do something to your database
}
else {
//return invalid payment
}
}
I suppose Route::post('/rave/callback', 'RaveController#callback')->name('callback'); Is your problem. It should be Route::get
Hi. I am sorry for editing this directly as I cant find the reply button. Route::get() returns null for this particular implementation.

How get lot of params from url but without (&)?

For now in Laravel i am testing url and in route i have
Route::group(['prefix' => 'game'], function (){
Route::get('/location/{location?}/action/{action?}/screen/{screen?}','GameController#index')->name('game.index');
});
In controller when i wanna pass params i have to type
example.com/game/location/1/action/update/screen/main
if i wanna pass only location and screen i have an error cause in url second param should be action.
I can create url like
example.com/game/?location=1&screen=main
and controller $request->screen and location works fine. But is any way to not using & ? and do this like:
example.com/game/location/1/screen/main
For this route
Route::get('/locations/{location?}/actions/{action?}/screens/{screen?}','GameController#index')->name('locations.actions.screens.show');
In GameController index method, you can get these parameter as
public function index(Location $location, Action $action, Screen $screen) {
// here you can use those models
}
if you are using route-model binding,
if not using
public function index($location, $action, $screen) {
// here you can use these variables
}
If the route name is locations.actions.screens.show then in view, it will be
Test
Now, if you have some query parameter
then it will be like $http://example.com/?test="some test data"&another_test="another test"
you can access these parameter like
public function myfunction(Request $request) {
dd($request->all());
}
Let's consider you want to retrieve all games, that belongs to a particular screen which belongs to a particular action and that belongs to a particular location, what your urls seems to be in your question, in that case, the url will be
Route::group(['prefix' => 'game'], function (){
Route::get('locations/{location?}/actions/{action?}/screens/{screen?}','GameController#index')->name('game.index');
});
url seems to be game/locations/1/actions/1/screens/1 where action and screen parameter can be optional
now in your controller index() method
public function index(Location $location, Action $action=null, Screen $screen=null) {
//using the model instance you received, you can retrieve your games here
}
Your error makes sense
URL second param should be action
because your route is with wild card location, action, screen
Route::group(['prefix' => 'game'], function (){
Route::get('/location/{location?}/action/{action?}/screen/{screen?}','GameController#index')->name('game.index');
});
To access this route you have to generate a URL with a wild card like
example.com/game/location/1/screen/main
and example.com/game/?location=1&screen=main not going to work because of your route URL and you can't access like $request->screen.
so your controller must be like
public function index($reuest, $location, $action, $screen){
}
You can directly access $location, $action, $screen and if you request something like
example.com/game/location/1/screen/main?param1=1&param2=2
Those are accessible through request like
$request->param1 and $request->param2
Occasionally you may need to specify a route parameter, but make the presence of that route parameter optional. You may do so by placing a ? mark after the parameter name. Make sure to give the route's corresponding variable a default value:
Route::get('user/{name?}', function ($name = null) {
return $name;
});
you can use Pattern Based Filters
You may also specify that a filter applies to an entire set of routes based on their URI.
Route::filter('admin', function()
{
//
});
Route::when('admin/*', 'admin');

Error when trying to return Redirect in Laravel

When I submit a form in Laravel, the following controller method handles it:
public function update($id)
{
//handle input
return View::make('generic.success', ["message" => 'Data submitted successfully!']);
}
This works fine. However, instead of returning a view like above I'd like to return a redirect, because when I return the view directly, reloading the page resubmits the form.
So I tried to do this:
public function update($id)
{
//handle input
return Redirect::to('/success', ['message' => 'Data submitted successfully!']);
}
In my routes file I defined the success route:
Route::get('success', 'NotificationsController#success');
And set up a notification controller to display the view:
class NotificationsController extends BaseController {
public function success($message)
{
return View::make('generic.success', ["message" => $message]);
}
When I run the above code, I get the following error from Laravel:
InvalidArgumentException
The HTTP status code "1" is not valid.
I have no idea what this is supposed to tell me, and neither does Google apparently.
Can someone shed some light on this issue?
P.S.
Incidentally, being new to Laravel, I've noticed so far that Laravel's error reporting is very user-unfriendly, in that instead of telling me I have an issue with my router, or controller, or permissions, it displays these generic errors with no humane explanation of their cause. Is there a better way to troubleshoot problems in Laravel than relying on this?
For example, in the above incident, the error report points to this line of code...
public function setStatusCode($code, $text = null)
{
$this->statusCode = $code = (int) $code;
if ($this->isInvalid()) {
throw new \InvalidArgumentException(sprintf('The HTTP status code "%s" is not valid.', $code));
}
...which is completely useless, as all it does is show me the code that printed the error itself.
The second parameter of the redirector's to() method is the HTTP status code that will be returned by the response, not data that will be passed along. Passing data when redirecting to GET routes can be done either via the query string or the session. The recommended solution here is to pass data via the current session using the with() method which passes that data for the next request. So in your case this would be the approach needed:
public function update($id)
{
return Redirect::to('/success')->with('message', 'Data submitted successfully!');
}
Then in your success method you can have this:
public function success($message)
{
return View::make('generic.success', ["message" => Session::get('message')]);
}
When in doubt always try checking the documentation first. The solution to this is explicitly stated in the Laravel Response Redirects Documentation.
Thanks a lot -Bogdan I found in the documentation that you post answer to my problem. In my case the solution was redirect to an action in a controller, like this...
return
\Redirect::action(
'PqrController#solicitud',
array($id)
)
->with(
'message',
'¡El estado de la solicitud ha sido actualizado correctamente!'
)
;
I redirect to a method in a controller, with one parameter array($id) and I put too in the session a message using ->with('message','Mensaje')

Zend _forward doesn't work after failed authentication (Zend Framework 1)

After a user fails authorisation I'd like to forward them back to the login page. Currently the _forward method causes Zend to hang and give a time out error (30 seconds exceeded).
The code for the login page handles both a login and signup form, and forwards to the authorisation controller:
public function indexAction() {
if ($this->_request->isPost()) {
$formData = $this->_request->getPost();
if (array_key_exists('signUp', $formData)) {
$authAction = 'signup';
$form = 'signupForm';
} elseif (array_key_exists('logIn', $formData)) {
$authAction = 'login';
$form = 'loginForm';
}
if ($this->$form->isValid($formData)) {
$this->_forward($authAction, 'user-auth', null, $formData);
} else {
$this->$form->populate($formData);
}
}
}
This works fine and redirects to the auth controller successfully. The code inside the login action of the auth controller is as such:
public function loginAction() {
$formData = $this->_request->getPost();
$authAdapter = new My_Auth_Adapter();
$authAdapter->setTableName('user')
->setIdentity($formData['username'])
->setCredential($formData['password'])
->setIdentityColumn('username')
->setCredentialColumn('password');
$result = $authAdapter->authenticate();
if ($result->isValid()) {
// success, all good
} else {
$this->_forward('index', 'login', 'default', $formData);
}
}
We arrive here fine, and a successful authorisation works as expected. However in my else statement placing another forward back to the original login controller (I wish to populate the username as well as post back an error message) causes the program to hang, although a redirect works fine.
I thought it may be because the login controller is re-detecting the post data and I'm getting caught in an infinite loop, but removing the $formData as the last argument of the forward doesn't change anything.
I've also tried $formData['errMsg'] = 'whatever' above the forward and then checking if the key exists or if it is set in the login controller, but that doesn't change a thing either.
Interestingly, the time out error I receive references the Auth DbTable Adapter:
Fatal error: Maximum execution time of 30 seconds exceeded in /Applications/MAMP/MampServer/mysite/library/Zend/Auth/Adapter/DbTable.php on line 174
Any ideas as to what may be happening?
I think you are infinity looping between loginAction() and indexAction().
Check out the difference between the calls to forward() and redirect() action helpers. The former, forward() internally will change the $request->isDispatched() == false - This means that the front controller will execute the targeted controller action without a new HTTP request.
The outcome of this is that $this->_request->isPost() will always be true and therefore $this->$form->isValid($formData) again will also be true, meaning your going around in circles.
I know the below is a very different to your approach, however I believe it is a more conventional separation of concerns for Zend 1 controllers.
// ... SomeController.php
public function getLoginForm();
public function getSignupForm();
protected function authenticate($username, $password)
{
$authAdapter = new My_Auth_Adapter();
$authAdapter->setTableName('user')
->setIdentity($username)
->setCredential($password)
->setIdentityColumn('username')
->setCredentialColumn('password');
$result = $authAdapter->authenticate();
return ($result->isValid()) ? true : false;
}
public function indexAction()
{
$form = $this->getLoginForm();
$request = $this->getRequest();
if ($request->isPost()) {
if ($form->isValid($request->getPost())) {
if ($this->authenticate($form->getValue('username'), $form->getValue('username'))) {
$this->redirect('/members'); // Successfully logged in
}
}
}
$this->view->form = $form;
}
public function signupAction()
{
// stuff only for signups!
}
Edit To elaborate: forward() is a controller action helper. Its job is simply to modify the Zend_Controller_Request_Http instance. The Zend_Controller_Request_Http class is the one returned when you call $this->getRequest() within a controller.
The Request instance encapsulates all access to $_POST, $_GET and stores then as values within the object. Calls such as $request->setParam('someparam', 123) set or get these values rather than the standard direct access to $_POST['someparam'] or $_GET['someparam'].
The special case is with the values module,controller,action and dispatched. These are the key's used by the Zend_Controller_Front and the Dispatcher when trying to determine the correct controller to instantiate and action method to execute.
A simplified example of how the dispatch loop works:
while(! $request->isDispatched()) {
$request->setDispatched(true);
// If at any point here we change setDispatched(true)
// perhaps in a controller action with a call to forward()
// then the whole dispatch loop will be called again
// perhaps creating a different controller
$controllerName = $request->getControllerName();
$actionName = $request->getActionName();
$controller = new $controllerName();
$controller->$actionName();
}
In the else block:
$this->_redirect($this->url(array('login' => $formData['username'], 'nameOfYourRoute'));
Added a new get variable 'login' to your route and populate your forms login with this variable.

Dealing with URI after $dispatcher->forward() execution

I've set form submission URI to something like '/register' and in controller action $dispatcher->forward() to '/profile'. When submitting form, it forwards to the right page, but URI shown in browser is '/register'. Is there a way to set URI to those defined in $dispatcher->forward() method and not in form action?
You can use the redirect method.
So in your controller you could do:
public function registerAction()
{
$this->view->disable();
if ($this->request->isPost()) {
// Here is where you process the POST and check the user
if ($user) {
// Valid user
$this->flash->success('OK');
return $this->response->redirect('profile');
} else {
$this->flash->error('Oops! Something went wrong.');
}
}
}

Categories