How to pass array of GET parameters to the controller?
This is my route file routes/web.php:
<?php
use Illuminate\Support\Facades\Route;
use GuzzleHttp\Client;
Route::get('/ids', 'Parser#getIds');
And my controller 'app/Http/Controllers/Parser.php':
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class Parser extends Controller
{
public function getIds(Request $request) {
return response()->json($request); // ???
}
}
So, I expect to get an array of parameters like this:
$ids = [1,2,15,25];
But if I pass GET array to my route path: http://example.com/ids?ids[]=1&ids[]=2&ids[]=15&ids[]=25
I get an empty request object anyway:
{"attributes":{},"request":{},"query":{},"server":{},"files":{},"cookies":{},"headers":{}}
There is few ways to get data from GET.
Try something like that:
$ids = request('ids', []); // global helper, empty array as default
or:
$ids = $request->input('ids', []); // via injected instance of Request
More info you can get in documentation
Related
I am calling a php file using in laravel controller. While calling the file I passing few data using ajax call. I want to print the variable that is passed to the controller file. Below is my code-
function handleJSON(originePlaceID, destPlaceID){
var elements = document.getElementsByClassName('waypoints'); //getting the values from input field
var wayptArray = new Array();
for(var i = 0; i < elements.length; i++){
if(elements[i].value != "") {
wayptArray.push(elements[i].value);
}
}
var JsonWaypt = JSON.stringify(wayptArray);
$.ajax({
type: "GET",
url: "placeIdApi",
data: {data : JsonWaypt, _token: '{{csrf_token()}}'},
cache: false,
success: function(places){
console.log(places);
}
});
}
My web.php file:
Route::get('/placeIdApi', 'placeId#index');
My controller file(placeId.php)
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class placeId extends Controller
{
public function index(Request $request){
$values = $request->data; //I want to print this $values variable.
}
}
Can anyone suggest me how to print this $request or $values variable? Thanks in advance.
For your purposes, the dd method would definitely be the best, so something like this should work:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class placeId extends Controller
{
public function index(Request $request){
$values = $request->data;
//Print the values
dd($values);
}
To see the result of this print, open up your Browser's console and go to the Networking section. Check the packet related to your request. The dd content should be printed into the preview for your request packet.
If you are trying to output the $values value as JSON to use in your AJAX request, it might be best to do something like this:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class placeId extends Controller
{
public function index(Request $request){
$values = $request->data; //I want to print this $values variable.
return response()->json($values);
}
}
That will allow your js function to use the data that is return in the response.
To just print out the value as others have suggested, you can use the dd function:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class placeId extends Controller
{
public function index(Request $request){
$values = $request->data; //I want to print this $values variable.
dd($values);
}
}
Then you can navigate to your defined route http://example.com/placeIdApi to see the echo'd out data.
You can dump $value like this:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class placeId extends Controller
{
public function index(Request $request){
$values = $request->data; //I want to print this $values variable.
dd($values); // die and dump $values
}
}
you can use dump method
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class placeId extends Controller
{
public function index(Request $request){
$values = $request->data; //I want to print this $values variable.
dump($values); // dump $values
//OR JSON RESPONSE
return response()->json($values);
}
}
Routes.php
use Illuminate\Http\Request;
Route::get('/age/{val}','AgeController#store');
AgeController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
class AgeController extends Controller
{
//
public function store(Request $request)
{
$data = $request->input('val');
var_dump($data);
}
}
My url is localhost/lara/public/age/20.
but
output:array(0) { }
When I change $request->input('val',500);
then output: int(500)
How to get 20 (val) in controller? Why array empty?
If your controller method is also expecting input from a route parameter, simply list your route arguments after your other dependencies. Add $val as the 2nd parameter in you store function. In your case it should be
public function store (Request $request,$val){dd($val);}
I have a base controller that gets certain default properties based on the domain name for every request. These include app_id and language_id.
What would be the recommended way to get these values set in my models, so that for example if I tried to create a new Post model it would have the app_id and language_id set by the values defined in my base_controller.
Kind regards to any response.
You can use sessions to store your app_id and language_id, and get it from session whenever you need it.
Check How to use sessions in Laravel from here
You can use __consruct method as suggested in comment.
Here is another alternative:-
YourController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\YourModel;
class YourController extends Controller
{
public function callModelStaticMethod()
{
$data = ['appId'=>4, 'languageId'=>5];
YourModel::passDataToModelMethod($data);
}
}
YourModel.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class YourModel extends Model
{
public static function passDataToModelMethod($data)
{
var_dump($data);
// Write your business logic here.
// $newObj = new self;
// $newObj->app_id = $data['app_id'];
// $newObj->language_id = $data['languageId'];
// $newObj->save();
}
}
#ravi...just bit correction to your code. you can't call directly your method from model.
YourModel::passDataToModelMethod($data);
above won't work, you need to do as follows
$insertData=new YourModel();
$insertData->passDataToModelMethod($data);
I have controller class in laravel in which i have a function create() and a variable attachment i am calling function by ajax
my class code is.
class AttachmentController extends Controller
{
public $_attachments;
public function create()
{
$this->_attachments[]= 'test';
var_dump($this->_attachments);
}
problem is every time when i call it by ajax it return me "test" at 0 index of attachment array . but i want if i call create function 1st time it give me test on 0 index but when next time when i call it . it give me "test" on both 0 and 1 index and so on ..
how it is possible please help me
To preserve the values between requests you need to store them somewhere, an alternative is to use sessions, as the example below, for more information see https://laravel.com/docs/session
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class AttachmentController extends Controller
{
public function create(Request $request)
{
$request->session()->push('attachments', 'test');
var_dump($request->session()->get('attachments'));
}
}
Try something like this.
$_attachments[] = Session::get('test');
$_attachments[] = 'test';
Session::get('test', $_attachments);
dd(Session::get('test'));
let me know if this is what you want.
Since HTTP driven applications are stateless, sessions provide a way
to store information about the user across requests.
class AttachmentController extends Controller
{
public function create()
{
$attachments = Session::get('attachments', array());
$attachments[] = 'test';
Session::put($attachments);
var_dump($this->_attachments);
}
}
Further reading: Laravel Session
When i redirect a route, Can't access to request data.
This is the ajax request informations:
Content-Type: application/x-www-form-urlencoded
param1=my+param&request=search
routes.php
use Illuminate\Http\Request;
Route::any('/items/search', 'ItemsController#search');
Route::any('/items', [
function(Request $request){
if ($request->input('request') == 'search') {
// echo $request->input('param1'); // returns param1 value correctly
return redirect()->action('ItemsController#search')->withInput();
}
}
]);
And this is controller:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;
class ItemsController extends Controller
{
public function search(Request $request)
{
var_dump($request->all()); // returns: array(0) { }
}
}
How can i access post data in controller, after redirect?
The method withInput adds the input to the Session. You can access it in the controller using $request->session->all().
That being said, a more RESTful way to do it is to have one route /items and in your controller you decide whether to filter results based on input parameters or not.
Try this
return redirect()->route('/items/search')->withInput();