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

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.');
}
}
}

Related

Redirect to route not redirecting in laravel

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);
}

login page in two places. for each other redirect

I make an online store in which I have two login places. /checkout (in cart) and /login.
Can i do it in the existing method to make redirect look like this?
if i login in /checkout ->redirect('/checkout').
(for loggin in /login) it stays like it is /redirect('/')
I would solve that by using the redirectTo() method in the Login Controller and checking which route is sending the request through the path() method. You have to name the routes for it to work though. So in your login Controller you'll have this;
use Illuminate\Support\Facades\Route;
protected function redirectTo(){
if(Route::currentRouteName() == 'login'){
return '/';
}else if(Route::currentRouteName() == 'checkout'){
return '/checkout';
}
}
more info on how to get the route name here
and info on the redirectTo() function here
Try it out, tell me what happens..
only this solution works:
protected function redirectTo() {
if(strpos(URL::previous(), 'checkout')) {
return '/checkout';
} elseif(strpos(URL::previous(), 'login')) {
return '/';
}
}

How to determine if a session with same variable is already there in laravel

I am using Laravel framework. There is a function in controller that creates session with name store_id
StoreController.php
function initiate($id)
{
//Some queries
session['store_id' => 'some value'];
}
Now if I run this function on one tab then session::get('store_id') is going on. But if I open another tab in the same browser then again run the function that means session('store_id') will be again set. How do I handle this situation that if there is already a session then it should redirect to it's perspective url.
Okay first of all, Bruuuhhhh been there and done that
Alright, lets begin. you want that if there is already a session with store_id going on then you want user to redirect or send back.
In your controller add this
public function initiate()
{
if(session()->has('store_id'))
{
//What ever your logic
}
else
{
redirect()->to('/store')->withErrors(['check' => "You have session activated for here!."]);
}
}
Most probably you would be wondering that user can just go to other url after /store/other-urls Yess he can.
To avoid this. Add a custom middleware
php artisan make:middleware SessionOfStore //You can name it anything.
In that middleware
public function handle($request, Closure $next)
{
if($request->session()->has('store_id'))
{
return $next($request);
}
else
{
return redirect()->back()->withErrors(['privilege_check' => "You are not privileged to go there!."]);
}
return '/home';
}
in your main store page. Add an anchor tag Stop Service
Now in your web.php
Route::group(['middleware' => 'SessionOfStore'], function()
{
//Add your routes here.
Route::get('/stop', 'StoreController#flushSession');
});
Now you have restrict access to urls and has checked the sessions.
Now in
public function flushSession()
{
//empty out the session and
return redirect()->to('/home');
}
The Laravel session helper has the function has to check this.
if (session()->has('store_id'))
{
// Redirect to the store
}
else
{
// Set the store id
}
The documentation contains all of the possible functions that can be used with the session helper.

Redirect and pass data from controller

I want to redirect from a controller and pass data;
public function fortest(Request $request)
{
$user = DB::table('user2s')->where('name', $request->name)->first();
if (isset($user))
{
return redirect('/fortest2', ['user'=>$user]);//compact('user'));
//return $this->fortest2($request);
}
}
public function fortest2(Request $request)
{
return $request->name;
}
Route::get('/fortest', 'UserController#fortest');
Route::get('/fortest2/', 'UserController#fortest2');
The code works when calling the controller directly from within the controller. The data type has a model. How can I accomplish this?
If you want to pass data in a redirect, you can use the with() method.
You have to append it to the redirect like so:
redirect('/fortest2')->with('data', 'value');
It will be saved in your current session, so it will be only persistent until you refresh the page again. If you want to store it for longer you have to go with a database/textfile etc. You can then check for it using
if (session()->has('data')) { // check if it exists
$value = session('data'); // to retrieve value
}
You can also send errors with the redirect (from validation i.e.) using withErrors(), sending the current input with it using withInput()
For what you want to achieve, try using this in your controller. This will just send the users name with the redirect:
$user = DB::table('user2s')->where('name', $request->name)->first();
redirect('/fortest2')->with('username', $user->name);
You can then access is via session('username')
You need to use sessions to pass data when using redirect:
return redirect('/fortest2')->with('data', 'some data');
Then get data from session:
$data = session('data');
Or you can persist data in DB and then get it from there.
Try to do like this
public function fortest(Request $request)
{
$user = DB::table('user2s')->where('name', $request->name)->first();
if(isset($user))
{
return redirect('/fortest2/$user->name');
}
}
public function fortest2($name)
{
return $name;
}
Your route
Route::get('/fortest', 'UserController#fortest');
Route::get('/fortest2/{$name}', 'UserController#fortest2');

How to stop execution of a Request in Kohana?

Let's say I have a controller template with a before function like so...
public function before()
{
parent::before();
if ($this->request === Request::instance())
{
// its a main request, throw an exception or redirect
Request::instance()->redirect('/');
}
else
{
// ok
}
}
But let's say I don't want to redirect, I want to stop the Request flow, and do nothing.
Does an exception do this? Is there a simple way, like Request::die();?
EDIT:: I actually don't want to halt the Request flow, just prevent this controller from doing anything. It's likely that this controller was called from another controller, and I want to pass the control back to the calling controller.'
Thanks!
1.Use exceptions (not tested yet):
try
(
Request->instance()->execute();
}
catch (MyRequest_Exception $e)
{
// do what you want
}
echo Request->instance()->send_headers->response();
// somewhere in before()
if ($error)
{
throw new MyRequest_Exception($errortext);
}
Change action name:
$this->request->action('oblivion'); // redirects to an "oblivion" action that does nothing
You can set a class variable in before() say:
$this->execute = false;
Then in your action:
public function action_example()
{
if (!$this->execute) return;
// etc
}

Categories