Input or Request are always empty in controllers - php

I need some help on a topic that is making me crazy on Laravel 5.2
I have the following routes.php, which I have reduced to the minimum :
use Illuminate\Http\Request;
/**
* Category Page
*/
Route::get('/category/test/', function()
{
dd("I'm in !");
dd(Input::all());
$page = Input::get('page');
if(isset($page)){
dd($page);
}
}
When I call the following url : http://192.168.99.100/category/test?page=55, I would expect to get the parameter page in Input or Request but however it is always empty. The following code just displays "I'm in !" but nothing else.
Can you help me understanding what is wrong in here ? I previously used controllers and Request parameters but it was also empty, thus this simple test. Note that post requests are working fine.
Thanks !

I finally found it out !
That was a problem in my nginx configuration, that prevented php variable QUERY_STRING to be correctly set up and Laravel is basing on this variable to retrieve the data.
For more information, see https://serverfault.com/questions/231578/nginx-php-fpm-where-are-my-get-params/362924#362924
Thaks for your answers anyway !

You can use both , actually there is no error in your code except if you missed the use statement for Input facade.
use Illuminate\Http\Request;
/**
* Category Page
*/
Route::get('/category/test/', function()
{
dd(Input::all());
dd("I'm in !");
$page = Input::get('page');
if(isset($page)){
dd($page);
}
}
So question is why you are getting nothing! because the route is GET request so if you post/update/patch anything to it you will get methodNotAllowed exception. Now just goto your browser and type http://whateverdomain/category/test/?page=atiq&have=fun and yes now there is something.........
Route::get('/category/test/', function(Request $request)
{
$input=$request->All();
dd($input);
$page = request->get('page');
if(isset($page)){
dd($page, request->get('have'));
}
}

because you didn't told function to expect request
it shall be
Route::get('/category/test/', function(Request $Request)
{
$input=$Request->All();
dd($input);
// usage $input['query'];
$page = Input::get('page');
if(isset($page)){
dd($page);
}
}

Related

Retain http method on redirect

I wrote localisation helper in laravel which checks whether en, fr or another local is in the URI.
If no locale is supplied config("app.locale") should be prepended to the original URI and a redirect should be made to this new URI. I.e. /user should be redirected too /en/user.
I am currently trying to resolve this problem by using:
public function handle($request, Closure $next, $guard = null)
{
$langSegment = $request->segment(1);
// if first segment is language parameter then go on
if (strlen($langSegment) == 2 && ($langSegment == 'en' || $langSegment == 'fr')) {
App::setLocale($langSegment);
return $next($request);
} else {
$newURL=url(config("app.locale") . "/" . implode("/",$request->segments()));
return redirect($newURL);
}
}
This works fine for most request unless the method is POST and there is no $language set. When this is the case the user is redirect but the method is changed to a POST request.
I also tried changing my redirect to
return redirect()->route('routeName', $request->all(), 302, ['method','POST'])
But this also doesn't work.
So I did some testing with regards to the HTTP status code 307.
Let me first describe my test setup, I created the following routes:
Route::get("/help", 'HelpController#index');
Route::post("/post", 'HelpController#post');
Route::post("/redirected", 'HelpController#redirected');
The HelpController contained the following code:
<?php
namespace App\Http\Controllers;
class HelpController extends Controller
{
public function index(){
return view('help');
}
public function post(){
return redirect('/redirected', 307);
}
public function redirected(){
echo "Success";
}
}
and help.blade.php was a very basic form namely:
<form method="post" action="/post">
#csrf
<button>Go</button>
</form>
I am glad to report that a 307 return code does successfully keep the POST method.
I.e. when I went to the /help url and pressed the "Go" button I saw the "Success" message as expected.
What does this mean for me you might ask?
Well we can solve your problems with a very simple change:
return redirect($newURL);
becomes
return redirect($newURL, 307);
Wasn't that easy in the end?
Furthermore as you can see in my test setup this also keeps the crsf protection which is a definite plus from a security standpoint.

Laravel allow route to be accessible only from another route

I have /signup/select-plan which lets the user select a plan, and /signup/tos which displays the terms of services. I want /signup/tos to be only accessible from /signup/select-plan. So if I try to go directly to /signup/tos without selecting a plan, I want it to not allow it. How do I go about this?
In the constructor, or the route (if you are not using contructors), you can check for the previous URL using the global helper url().
public function tos() {
if ( !request()->is('signup/tos') && url()->previous() != url('signup/select-plan') ) {
return redirect()->to('/'); //Send them somewhere else
}
}
In the controller of /signup/tos which returns the tos view just add the following code:
$referer = Request::referer();
// or
// $referer = Request::server('HTTP_REFERER');
if (strpos($referer,'signup/select-plan') !== false) {
//SHOW THE PAGE
}
else
{
dd("YOU ARE NOT ALLOWED")
}
What we are doing here is checking the HTTP referrer and allowing the page access only if user comes from select-plan
You are need of sessions in laravel. You can see the following docs to get more info: Laravel Sessions
First of all you need to configure till how much time you want to have the session variable so you can go to your directory config/sessions.php and you can edit the fields 'lifetime' => 120, also you can set expire_on_close by default it is being set to false.
Now you can have following routes:
Route::get('signup/select-plan', 'SignupController#selectPlan');
Route::post('signup/select-token', 'SignupController#selectToken');
Route::get('signup/tos', 'SignupController#tos');
Route::get('registered', 'SignupController#registered');
Now in your Signupcontroller you can have something like this:
public function selectPlan()
{
// return your views/form...
}
public function selectToken(Request $request)
{
$request->session()->put('select_plan_token', 'value');
return redirect('/signup/tos');
}
Now in signupController tos function you can always check the session value and manipulate the data accordingly
public function tos()
{
$value = $request->session()->get('select_plan_token');
// to your manipulation or show the view.
}
Now if the user is registered and you don't need the session value you can delete by following:
public function registered()
{
$request->session()->forget('select_plan_token');
// Return welcome screen or dashboard..
}
This method will delete the data from session. You can manipulate this. You won't be able to use in tos function as you are refreshing the page and you want data to persist. So its better to have it removed when the final step or the nextstep is carried out. Hope this helps.
Note: This is just the reference please go through the docs for more information and implement accordingly.

yii2 login page redirection looping with cancelled status

After spending so many days, am trying to get some help from experts.
I am stuck with login redirection in my yii2 application only in chrome browser,
This is my controller class,
class InvitationsController extends Controller
{
public function beforeAction($action)
{ $array=array('index','imageupload','template','category','subcategory','slug','chooseanotherdesign');
if(!in_array($action->id, $array))
{
if (\Yii::$app->getUser()->isGuest &&
\Yii::$app->getRequest()->url !== Url::to(\Yii::$app->getUser()->loginUrl)
) {
\Yii::$app->getResponse()->redirect(\Yii::$app->getUser()->loginUrl,FALSE);
}
}
return parent::beforeAction($action);
}
public function actionGenerateevent(){
$redirectUrl="";
if(Yii::$app->request->post()){
unset(Yii::$app->session['copyinvitation']);
unset(Yii::$app->session['eventform']);
Yii::$app->session['eventform']=Yii::$app->request->post();
}
if (!Yii::$app->user->isGuest)
{
$eventid=$this->invitation->savecontinue(Yii::$app->session['eventform']);
$eventdata=$this->invitation->getEventById($eventid);
$refurl=Yii::$app->session['eventform']['refererurl'];
$aa['Events']=$eventdata;
$aa['refererurl']=$refurl;
Yii::$app->session['eventform']=$aa;
$redirectUrl = Yii::$app->urlManager->createAbsoluteUrl(['invitations/event/'.$eventdata['event_token']]);
return $this->redirect($redirectUrl);
}
}
}
My workflow
step1: submitting formdata to controller xx-action
step2: If user login it will proceed further action
Else
am trying to store the values in session then redirecting the page to login
step 3: after successful login am return back to same xx-action
This workflow is working fine in firefox but chrome it's making infinitive loop its not going through the login page.
Please refer am attached the screenshot
Please help me to solve this issue.
I can't infere how are you calling your actionGenerateevent() but you seems to have an error there:
$redirectUrl=""; //empty
...
return $this->redirect($redirectUrl); //still empty
Since you are not setting your $redirectUrl, your redirect is redirecting you to the current (same) url again and again, causing the loop.
This is the function used by redirectUrl() method: Url::to(). Its docs says:
an empty string: the currently requested URL will be returned;

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

Codeigniter routes for passing get parameter to index function

I have a url www.mywebsite.com/store/123456
where store is my controller class and I have a index function in it where Im getting the value after after store ,ie 123456.But im not able to achieve it.
As found online,I have tried adding this to routes $route['store/(:any)'] = 'store/index'; also tried
$route['store/(:any)'] = 'store/index/$1';
but doesn't seem to work.Please help me out.
In controller index function is
public function index()
{
echo $this->uri->segment(1);
}
But its not working.Pleae help
You are invoking 123456() method instead of index() method therefore you get CI's 404.
The simplest way is to use this kind of route
$route['store/(:any)'] = 'store/index/$1';
AND in top of it add parameter to index function in your case
public function index($parameter)
{
echo $this->uri->segment(2);
}
note that I changed segment parameter please see documentation.
using _remap()
function _remap($parameter){
$this->index($parameter);
}
function index($p)
{
echo $p; //shows 123456
}
If I remember correctly:
segment(n) gives you the segments of your uri before the routing takes place
rsegment(n) gives you the segments of your uri after routing (if routing occurred or the same as segment if it didn't)
so for /store/123456 getting rerouted to /store/index/123456
segment(1) == rsegment(1) == 'store'
rsegment(2) == 'index'
segment(2) == rsegment(3) == '123456'
Route:
$route['terms_and_conditions'] = 'SO_front/page/1';
controller :
public function page($id)
{
echo $id;
}
Output :
1
Here my solution for CI3...i would prefer laravel for advanced routing, orm,restapi, build in vuejs.
$route['store/(:any)'] = 'store/index/';
public function your index(){
$parameter=$this->uri->segment(2);
//use parameter for sql query.
}
Let say your route $route[store/product/update/(:any)] , then $parameter=$this->uri->segment(4)
Problem?. You will need to change entire file code if you plan to change the route name include view, controller, and custom route.

Categories