I have an issue in my laravel app.
I want to sent an array to another route.
here is the code.
Controller:
$emparray =[
'fname'=>Input::get('efname'),
'lname'=>Input::get('elname'),
'dob'=>Input::get('edob'),
'reg_date'=>date('Y-m-d'),
'email'=>Input::get('eemailaddrs'),
'gender'=>Input::get('gender'),
'mobile'=>Input::get('emobile'),
'p_addrss'=>Input::get('epaddress'),
'c_addrss'=>Input::get('ecaddress'),
'quals'=>Input::get('quali'),
'pdfname'=>$pdfname,
];
return Redirect::to('print-view',$emparray);
Routes.php
Route::get('print-view/{$emparray}', array('as'=>'print-view','uses'=>'EmployeeController#PrintView'));
Final Controller.
public function PrintView($emparray)
{
return $emparray;
}
I Can't get the successful output. Is there any issues with my code.?
Getting error like "The HTTP status code "1" is not valid."
Thanks..
Use Redirect::to('print-view')->with($emparray);
You cant do it like this ,if you would check the to method you would see this -
public function to($path, $status = 302, $headers = [], $secure = null)
{
$path = $this->generator->to($path, [], $secure);
return $this->createRedirect($path, $status, $headers);
}
so basically you send the status parameter an array. to send parameters you will need to use the action/route methods
Why don't you call the PrintView method directly? I mean... why do you need to route all this data?
Related
I wonder how to use sequence in HTTP::fake call back.
What I want is to get a sequence of responses when the body of my request contains ListSupplierRoutes.
here is my code:
Http::fake(function (Request $request) {
$body = $request->body();
$xmlFileName = 'login';
if (Str::contains($body, 'Login')) {
$xmlFileName = 'login';
}
if (Str::contains($body, 'ListSupplierRoutes')) {
return Http::sequence()
->push($this->loadXMLResponse('list-supplier-routes-ryanair'))
->push($this->loadXMLResponse('list-supplier-routes-ezy'));
}
// Some other conditions
return Http::response($this->loadXMLResponse($xmlFileName));
});
With this approach I get the below exception:
BadMethodCallException : Method Illuminate\Http\Client\ResponseSequence::then does not exist.
/..../vendor/laravel/framework/src/Illuminate/Macroable/Traits/Macroable.php:103
.../vendor/laravel/framework/src/Illuminate/Http/Client/PendingRequest.php:730
.../vendor/laravel/framework/src/Illuminate/Http/Client/PendingRequest.php:707
.../vendor/guzzlehttp/guzzle/src/PrepareBodyMiddleware.php:64
.../vendor/guzzlehttp/guzzle/src/Middleware.php:37
.../vendor/guzzlehttp/guzzle/src/RedirectMiddleware.php:71
.../vendor/guzzlehttp/guzzle/src/Middleware.php:61
.../vendor/guzzlehttp/guzzle/src/HandlerStack.php:75
.../vendor/guzzlehttp/guzzle/src/Client.php:331
.../vendor/guzzlehttp/guzzle/src/Client.php:168
.../vendor/guzzlehttp/guzzle/src/Client.php:187
.../vendor/laravel/framework/src/Illuminate/Http/Client/PendingRequest.php:609
.../vendor/laravel/framework/src/Illuminate/Support/helpers.php:234
.../vendor/laravel/framework/src/Illuminate/Http/Client/PendingRequest.php:624
.../vendor/laravel/framework/src/Illuminate/Http/Client/PendingRequest.php:528
Make sure your $this->loadXMLResponse() is returning either a string or an array. Also, the Http::fake() requires that you pass an associative array of url mapping to Http::resonse() type or Http::sequence().
For instance
Http::fake(['http://stackoverflow.com' => Http::sequence()->push('OK', 200)->push('Bad Request', 400)])
In my web file, I have a route that accepts a $id as a value to be passed to a function within my PagesController. However, I want the function to still execute and show the intended form even when the $id is not passed to the function.
web.php file
Route::get('/request/{id}', 'PagesController#makeRequest');
PagesController.php file
public function makeRequest($id)
{
if(!empty($id)){
$target = Partner::find($id);
}
return view('pages.makeRequest')->with('target', $target);
}
makeRequest.blade.php
<input type="text" class="form-control" value="{{$target->inst_name}}" required disabled>
I want the page to display details from the database with the $id when provided or have empty spaces when the $id isn't provided.
As the Laravel Documentation states: Use Optional Parameters like this:
Route::get('/request/{id?}', 'PagesController#makeRequest'); //Optional parameter
Controller
public function makeRequest($id = null)
{
if(!empty($id)){
$target = User::find($id);
return view('pages.makeRequest')->with('target', $target);
} else {
return view('pageslist'); ///set default list..
}
}
This is the way I did it:
Route::get('index', 'SeasonController#index');
// controller
public function index(Request $request )
{
$id= $request->query('id');
}
The way you call it:
localhost/api/index?id=7
All your solutions were helpful. The main thing was that when I called just the view without passing $target to the view, the page displayed an error. So this is what I did.
Route::get('/request/{id?}', 'PagesController#makeRequest');
Then in the controller,
public function makeRequest(Request $request, $id=null)
{
if ($id != null) {
$target = Partner::find($id);
return view('pages.makeRequest')->with('target', $target);
}
return view('pages.makeNullRequest');
}
If you didn't understand what happened, I created a new view which had this instead of what I had posted in the question.
<input type="text" class="form-control" value="" required readonly>
Sorry I didn't update you guys in time. I think Jignesh Joisar came closest to helping me solve this issue. really appreciate all you guys. You're just awesome
You can use optional parameter :
Route::get('/request/{id?}', 'PagesController#makeRequest');
Now, as the parameter is optional, while defining the controller function you need to assign its default value to null in argument declaration.
<?php
public function makeRequest($id = null)
{
if($id){
$target = Partner::findOrFail($id);
return view('pages.makeRequest')->with(compact('target'));
}
// Return different view when id is not present
// Maybe all targets if you want
$targets = Partner::select('column1', 'column2')->get();
return view('pages.all')->with('targets');
}
I am using findOrFail instead of find. Its Laravel's very handy function which automatically throws a ModelNotFound exception and for frontend user throws a simple 404 page.
So if anyone is accessing www.url.com/request/2, its a valid id then it will show a valid page with data. If the accessed url is www.url.com/request/blahblah then it will throw 404. It avoids efforts of handling this manually.
For optional parameter pass id with ? in route and give $id = null in your function's parameter like this:
Route::get('/request/{id?}', 'PagesController#makeRequest'); //Optional parameter
makeRequest($id = null) {
// Code here...
...
}
in your routes file (web.php , as mentioned in your question)
Route::get('/request/{id?}', 'PagesController#makeRequest');
and in your controller PagesController.php
public function makeRequest($id = null)
{
}
To read more about this, just read https://laravel.com/docs/5.7/routing#parameters-optional-parameters
For me the answer was in the order that I listed the Routes in the routes file.
The routes file will call the first one that matches the pattern.
Route::get('/ohmy/{id?}', 'OhMyController#show');
Route::get('/ohmy/all', 'OhMyController#all'); //never gets called
Instead, put optional parameters at end of list:
Route::get('/ohmy/all', 'OhMyController#all');
Route::get('/ohmy/{id?}', 'OhMyController#show');
the answer has been said. just a side note: optional parameters won't work if you are using resource routes.
for example:
Route::resource('items',itemController::class)->except([
'create',
]);
Route::get('/items/create/{category_id?}',function($category_id = 'abc'){
dd($category_id);
});
if i go to " items/create/1 ", the result will be "1".
if i go to " items/create ", it will return 404. ( but we expect it to say "abc".)
this happens because other routes that start with "items" are expected to be generated from "resource" functionality.
so if you use resource routes, you should consider that.
I just can't retrieve the data in my query string section.
I've used AJAX request throughout my website to implement a wide variety of tasks asynchronously and didn't had an issue of this kind.
Route
Route::get('/mensagem/enviar_mensagem', [ 'as' => 'mensagem.enviar_mensagem', 'uses' => 'MensagemController#enviar_mensagem']);
the testing url:
http://mydomain.com.br/mensagem/enviar_mensagem?para=email#bol.com.br
my action method:
public function enviar_mensagem(Request $request)
{
$para = $request->get('para');
//$para = $_GET['para']; I get an undefined index error
echo $para; //always empty string!
}
You need to use input. Like so:
Also, for testing, return versus echo.
public function enviar_mensagem(Request $request)
{
$para = $request->input('para');
return $para;
}
And to spark my curiosity, what does return $request->all() return?
Well, the provided code seems to be correct. Make sure you use \Illuminate\Http\Request. This code
Route::get('/mensagem/enviar_mensagem', function(\Illuminate\Http\Request $request) {
return $request->para;
// return $request->get('para'); // also works
});
returns email#bol.com.br by request http://your-site.app/mensagem/enviar_mensagem?para=email#bol.com.br
I copy pasted your code and both works:
$para = $request->get('para');
$para = $_GET['para'];
//$para = $_GET['para']; I get an undefined index error
Did you make sure the webserver is properly handling the HTTP request?
https://laravel.com/docs/5.4#web-server-configuration
You can try with below code :
use Request;
class xyzController {
public function enviar_mensagem()
{
$para = Request::all();
echo $para['para'];
}
}
First you will need to change the route to add also this
Route::get('/mensagem/enviar_mensagem/{para}',
[ 'as' => 'mensagem.enviar_mensagem', 'uses' =>
'MensagemController#enviar_mensagem']);
And after that in controller
public function enviar_mensagem($para){
return var_dump($para);
}
Use the route method on the request object to access GET parameters
public function enviar_mensagem(Request $request)
{
$para = $request->route('para');
echo $para;
}
I want to redirect admins to /admin and members to /member when users are identified but get to the home page (/).
The controller looks like this :
public function indexAction()
{
if ($this->get('security.context')->isGranted('ROLE_ADMIN'))
{
return new RedirectResponse($this->generateUrl('app_admin_homepage'));
}
else if ($this->get('security.context')->isGranted('ROLE_USER'))
{
return new RedirectResponse($this->generateUrl('app_member_homepage'));
}
return $this->forward('AppHomeBundle:Default:home');
}
If my users are logged in, it works well, no problem. But if they are not, my i18n switch makes me get a nice exception :
The merge filter only works with arrays or hashes in
"AppHomeBundle:Default:home.html.twig".
Line that crashes :
{{ path(app.request.get('_route'), app.request.get('_route_params')|merge({'_locale': 'fr'})) }}
If I look at the app.request.get('_route_params'), it is empty, as well as app.request.get('_route').
Of course, I can solve my problem by replacing return $this->forward('AppHomeBundle:Default:home'); by return $this->homeAction();, but I don't get the point.
Are the internal requests overwritting the user request?
Note: I'm using Symfony version 2.2.1 - app/dev/debug
Edit
Looking at the Symfony's source code, when using forward, a subrequest is created and we are not in the same scope anymore.
/**
* Forwards the request to another controller.
*
* #param string $controller The controller name (a string like BlogBundle:Post:index)
* #param array $path An array of path parameters
* #param array $query An array of query parameters
*
* #return Response A Response instance
*/
public function forward($controller, array $path = array(), array $query = array())
{
$path['_controller'] = $controller;
$subRequest = $this->container->get('request')->duplicate($query, null, $path);
return $this->container->get('http_kernel')->handle($subRequest, HttpKernelInterface::SUB_REQUEST);
}
By looking at the Symfony2's scopes documentation, they tell about why request is a scope itself and how to deal with it. But they don't tell about why sub-requests are created when forwarding.
Some more googling put me on the event listeners, where I learnt that the subrequests can be handled (details). Ok, for the sub-request type, but this still does not explain why user request is just removed.
My question becomes :
Why user request is removed and not copied when forwarding?
So, controller actions are separated part of logic. This functions doesn't know anything about each other. My answer is - single action handle kind of specific request (e.g. with specific uri prarams).
From SF2 docs (http://symfony.com/doc/current/book/controller.html#requests-controller-response-lifecycle):
2 The Router reads information from the request (e.g. the URI), finds a
route that matches that information, and reads the _controller
parameter from the route;
3 The controller from the matched route is
executed and the code inside the controller creates and returns a
Response object;
If your request is for path / and you wanna inside action (lets say indexAction()) handling this route, execute another controller action (e.g. fancyAction()) you should prepare fancyAction() for that. I mean about using (e.g.):
public function fancyAction($name, $color)
{
// ... create and return a Response object
}
instead:
public function fancyAction()
{
$name = $this->getRequest()->get('name');
$color = $this->getRequest()->get('color');
// ... create and return a Response object
}
Example from sf2 dosc:
public function indexAction($name)
{
$response = $this->forward('AcmeHelloBundle:Hello:fancy', array(
'name' => $name,
'color' => 'green',
));
// ... further modify the response or return it directly
return $response;
}
Please notice further modify the response.
If you really need request object, you can try:
public function indexAction()
{
// prepare $request for fancyAction
$response = $this->forward('AcmeHelloBundle:Hello:fancy', array('request' => $request));
// ... further modify the response or return it directly
return $response;
}
public function fancyAction(Request $request)
{
// use $request
}
Hello I'm creating an API using REST and Laravel following this article.
Everything works well as expected.
Now, I want to map a GET request to recognise a variable using "?".
For example: domain/api/v1/todos?start=1&limit=2.
Below is the contents of my routes.php :
Route::any('api/v1/todos/(:num?)', array(
'as' => 'api.todos',
'uses' => 'api.todos#index'
));
My controllers/api/todos.php :
class Api_Todos_Controller extends Base_Controller {
public $restful = true;
public function get_index($id = null) {
if(is_null($id)) {
return Response::eloquent(Todo::all(1));
} else {
$todo = Todo::find($id);
if (is_null($todo)) {
return Response::json('Todo not found', 404);
} else {
return Response::eloquent($todo);
}
}
}
}
How do I GET a parameter using "?" ?
Take a look at the $_GET and $_REQUEST superglobals. Something like the following would work for your example:
$start = $_GET['start'];
$limit = $_GET['limit'];
EDIT
According to this post in the laravel forums, you need to use Input::get(), e.g.,
$start = Input::get('start');
$limit = Input::get('limit');
See also: http://laravel.com/docs/input#input
On 5.3-8.0 you reference the query parameter as if it were a member of the Request class.
1. Url
http://example.com/path?page=2
2. In a route callback or controller action using magic method Request::__get()
Route::get('/path', function(Request $request){
dd($request->page);
});
//or in your controller
public function foo(Request $request){
dd($request->page);
}
//NOTE: If you are wondering where the request instance is coming from, Laravel automatically injects the request instance from the IOC container
//output
"2"
###3. Default values
We can also pass in a default value which is returned if a parameter doesn't exist. It's much cleaner than a ternary expression that you'd normally use with the request globals
//wrong way to do it in Laravel
$page = isset($_POST['page']) ? $_POST['page'] : 1;
//do this instead
$request->get('page', 1);
//returns page 1 if there is no page
//NOTE: This behaves like $_REQUEST array. It looks in both the
//request body and the query string
$request->input('page', 1);
###4. Using request function
$page = request('page', 1);
//returns page 1 if there is no page parameter in the query string
//it is the equivalent of
$page = 1;
if(!empty($_GET['page'])
$page = $_GET['page'];
The default parameter is optional therefore one can omit it
###5. Using Request::query()
While the input method retrieves values from entire request payload (including the query string), the query method will only retrieve values from the query string
//this is the equivalent of retrieving the parameter
//from the $_GET global array
$page = $request->query('page');
//with a default
$page = $request->query('page', 1);
###6. Using the Request facade
$page = Request::get('page');
//with a default value
$page = Request::get('page', 1);
You can read more in the official documentation https://laravel.com/docs/5.8/requests
We have similar situation right now and as of this answer, I am using laravel 5.6 release.
I will not use your example in the question but mine, because it's related though.
I have route like this:
Route::name('your.name.here')->get('/your/uri', 'YourController#someMethod');
Then in your controller method, make sure you include
use Illuminate\Http\Request;
and this should be above your controller, most likely a default, if generated using php artisan, now to get variable from the url it should look like this:
public function someMethod(Request $request)
{
$foo = $request->input("start");
$bar = $request->input("limit");
// some codes here
}
Regardless of the HTTP verb, the input() method may be used to retrieve user input.
https://laravel.com/docs/5.6/requests#retrieving-input
Hope this help.
This is the best practice. This way you will get the variables from
GET method as well as POST method
public function index(Request $request) {
$data=$request->all();
dd($data);
}
//OR if you want few of them then
public function index(Request $request) {
$data=$request->only('id','name','etc');
dd($data);
}
//OR if you want all except few then
public function index(Request $request) {
$data=$request->except('__token');
dd($data);
}
Query params are used like this:
use Illuminate\Http\Request;
class MyController extends BaseController{
public function index(Request $request){
$param = $request->query('param');
}
In laravel 5.3 $start = Input::get('start'); returns NULL
To solve this
use Illuminate\Support\Facades\Input;
//then inside you controller function use
$input = Input::all(); // $input will have all your variables,
$start = $input['start'];
$limit = $input['limit'];
In laravel 5.3
I want to show the get param in my view
Step 1 : my route
Route::get('my_route/{myvalue}', 'myController#myfunction');
Step 2 : Write a function inside your controller
public function myfunction($myvalue)
{
return view('get')->with('myvalue', $myvalue);
}
Now you're returning the parameter that you passed to the view
Step 3 : Showing it in my View
Inside my view you i can simply echo it by using
{{ $myvalue }}
So If you have this in your url
http://127.0.0.1/yourproject/refral/this#that.com
Then it will print this#that.com in you view file
hope this helps someone.
It is not very nice to use native php resources like $_GET as Laravel gives us easy ways to get the variables. As a matter of standard, whenever possible use the resources of the laravel itself instead of pure PHP.
There is at least two modes to get variables by GET in Laravel (
Laravel 5.x or greater):
Mode 1
Route:
Route::get('computers={id}', 'ComputersController#index');
Request (POSTMAN or client...):
http://localhost/api/computers=500
Controler - You can access the {id} paramter in the Controlller by:
public function index(Request $request, $id){
return $id;
}
Mode 2
Route:
Route::get('computers', 'ComputersController#index');
Request (POSTMAN or client...):
http://localhost/api/computers?id=500
Controler - You can access the ?id paramter in the Controlller by:
public function index(Request $request){
return $request->input('id');
}