Passing posted values from one controller to another in symfony - php

I have two controllers. I find problem in passing posted values from one controller to another. Here is a quick view,
This is the function 1
public function setRole(request $request){
this->forward(Path,array(role=>$role));
this->redirect(path of second controller);
}
This is the function 2.
public function getRole(request $request){
$role = $request->get('role');//when printing this $role, I am able to get the value of $role.
$sql = "select * from table where id=$role"; // I cannot get the value in this qry ,also, i cannot pass the value to a twig file
return render...(filename,array('roleid'=>$role));
}
Problem is I could'n access the variable "roleid" in my twig file of second controller. Always it goes empty.
Is there anything i have missed here?

You have missed the Documentation :
public function indexAction($name) {
$response = $this->forward('AcmeHelloBundle:Hello:fancy', array(
'role' => $role
));
// ... further modify the response or return it directly.
// But do not redirect afterwards!
// Just return the response that the forwarded controller returns
return $response;
}

In case anyone else finds this from Googling. From Symfony 3.3 you can use the session interface to pass things from one controller to another.
As the documentation says: To retrieve the session, add the SessionInterface type-hint to your argument and Symfony will provide you with a session.
use Symfony\Component\HttpFoundation\Session\SessionInterface;
public function indexAction(SessionInterface $session)
{
// store an attribute for reuse during a later user request
$session->set('foo', 'bar');
// get the attribute set by another controller in another request
$foobar = $session->get('foobar');
// use a default value if the attribute doesn't exist
$filters = $session->get('filters', array());
}

Related

How to redirect different page from same controller function in laravel 5.2

I want to redirect 2 different page from this controller function along with value.Here is my code. It works but both of time url become same.what shuld I do?
//in routes.php
Route::post('/','mycontroller#check');
// in controller.php
public function check(Request $request)
{
$c_email = $request->email;
$c_pass=$request->pass;
$c_type=$request->select;
$var=DB::select("SELECT * FROM reg where email = '$c_email' and Password = '$c_pass' and type = '$c_type'");
if ($var) {
return view('farmer')->with('user',$var);
// return redirect('farmer')->with('user',$var);
}
else {
$msg="Invalid login";
return view('index')->with('show',$msg);
}
}
If you want to actually redirect u can use the redirect() helper as statet in the official docs https://laravel.com/docs/5.3/redirects
You can also pass data
redirect('/my-route')->with(['user' => $var]);
The passed data can then be accesses through the session helper
$var = session('user')
HOWEVER, it seems like you have major issues in your code. Your password does not seem to be encrypted. Also there's no reason to use plain sql instead of eloquent here.
The route that is shown in the browser is defined in your
Route::post('/','mycontroller#check');
If you just return different views, the route does not change. You need to redirect to other views.
If you redirect to other routes you will ofcourse need to add / define them.
Route::get('/my-route', function() {}); // or post etc.

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

Laravel 5.2.32: Session flash doesn't work with redirect

I have a controller which has a redirect function:
public function myControllerMethod()
{
$data = $this->blabla();
return Redirect::to('previousroute')->with('data', $data);
}
This previousroute is handled by otherControllerMethod() like so:
public function otherControllerMethod()
{
$data = Session::get('data');
return $this->makeView($data);
}
Unfortunately, Laravel forgets this session data. I've done this many times before and I have never seen if forget the session flash data after a single redirect. What is going on here? I have tried both adding and removing "web" middleware but nothing works. If anyone knows why this happens let me know.
use Session;
public function myControllerMethod()
{
$data = $this->blabla();
Session::set('data', $data);
return Redirect::to('previousroute')->with('data', $data);
}
public function otherControllerMethod()
{
$data = Session::get('data');
return $this->makeView($data);
}
Try like this. Use the session and set the data in session and get it from where you want.
I have had the same Issue before. Basically I needed to call send function when redirecting using Redirect facade. So you need to change your myControllerMethod to:
public function myControllerMethod()
{
$data = $this->blabla();
return Redirect::to('previousroute')->with('data', $data)->send();
}
As send() function of class Symfony\Component\HttpFoundation\Response calls the function sendContent() which sends the data when redirecting.
Hope this helps.
In myControllerMethod you are passing the data obj/var as a Request.
In otherControllerMethod you are requesting the Session data which is not set.
In order to put data to the session you should do:
Session::put('data','value')
and then it will be available with:
Session::get('data');

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.

How to check the existence DRY & Laravel-style of an object that many controller methods are working with?

In a Laravel controller I have a couple of methods that all begin by fetching a database record, then after checking if data has been found either continue by rendering a view, or, in case of no data, go to a 404 page.
Here's an example:
<?php
function get_show_user($id)
{
$user = static::get_user($user_id);
if (!$user) {
return Response::error('404', static::$some_common_error404_message);
}
return View::make('users.show_readonly_user_data')->with('user', $user);
}
function get_edit_user($id)
{
$user = static::get_user($user_id);
if (!$user) {
return Response::error('404', static::$some_common_error404_message);
}
return View::make('users.display_edit_user_form')->with('user', $user);
}
I'm repeating the entire if (!$user) statement in these methods, even if they all do the same thing.
I'd rather like to do something like this:
function get_show_user($id)
{
$user = Users::find($id);
static::go404_if_null($user);
return View::make('users.show_readonly_user_data')->with('user', $user);
}
function get_edit_user($id)
{
$user = Users::find($id);
static::go404_if_null($user);
return View::make('users.display_edit_user_form')->with('user', $user);
}
What would be the best way to implement such a DRY feature?
Obviously a simple return Response::error('404') would not work in the common existence checker method, since it would only return from that method.
It seems that an Event::fire('404') is not ideal either since it does not terminate the method it has been triggered in.
Perhaps using an exception would be required here, but I'm unsure about this, or how it should be done in Laravel. Where should I catch a 404 Exception of a controller?
I think the best way to approach this would be a before filter on your controller.
public static $require_user = array(
'edit_user',
'show_user',
);
public function before()
{
$route = Request::route();
if ( in_array( $route->controller_action, static::$require_user ) )
{
$this->user = User::find( $route->parameters[0] );
if ( is_null($this->user) ) return Response::error('404');
}
}
Before filters get called after your controller is constructed but before the method is called. If a before filter returns anything other than null, the method is not called and thus execution is stopped.
Here we obtain the current route being executed so we can check which method is going to be called against our array $require_user. This lets us use methods that don't require a user id, such as login.
Then we retrieve the user instance, getting the id from what would have been passed to the method. You should probably add more error handling here.
Lastly, we check if the user returned was null, meaning not found. If that is the case we return a 404 response, stopping execution of the method.
I hope this helps!

Categories