I am using Laravel routes to build a RESTful API. I am routing to a Controller. In it, my function "store()" (my post function) should be getting a JSON input and I'm testing it by simply returning it. I seem to be able to see the data being passed in by doing Input::get('data') but I can't do a json_decode on that. The value of the json_decode is simply null. Can anyone help me get a working example of POSTing to a route with JSON data and accessing the data?
Here's what I have:
Route
Route::post('_api/tools/itementry/items', 'ItemEntryController');
Controller
class ItemEntryController extends BaseController
{
//... other functions
public function store()
{
if(Input::has('data'))
{
$x = Input::get('data');
$data = json_decode($x);
var_dump($data);
}
}
}
I'm using a REST tester client to submit a post with the following Query string parameters:
Name: "data"
Value: { itemNumber:"test1", createdBy:"rsmith" }
This ended up being a really stupid problem. I was doing everything right, except my JSON that I was sending in the test client was formatted incorrectly. I forgot to add quotes around the key strings.
So, instead of doing { itemNumber:"test1", createdBy:"rsmith" }
I needed to do { "itemNumber":"test1", "createdBy":"rsmith" }
Now it works.
Related
This is my code of route for getting data from Laravel backend.
Route::get('/get/card',[CardController::class,'getCardList'])->name('card.list');
I call it like below,
http://127.0.0.1:8000/get/card
Controller code
public function getCardList()
{
//code goes here
}
The above code is working fine. I'm trying to add a parameter for adding filtration as follows;
Route::get('/get/card{treeItemID?}',[CardController::class,'getCardList'])->name('card.list');
public function getCardList($treeItemID)
{
}
http://127.0.0.1:8000/get/card?treeItemID=1
But, I'm getting the error "Too few arguments to function app\Http\Controllers\CardController::getCardList()..."
Can anyone notice what's wrong with my code that gives the above error when the parameter is added? Any help would be highly appreciated.
if you want to get data like below url, please replace your route and method like below and check again.
http://127.0.0.1:8000/get/card?treeItemID=1
Route::get('/get/card',[CardController::class,'getCardList'])->name('card.list');
public function getCardList(Request $request){
$treeItemID = $request->input('treeItemID');
return $treeItemID;
}
You can use get and post both type of request for filtering purpose.
Scenario 1 => If you want to hide some parameter inside request then you can use POST type of request where use can pass data in form data and get from request inside in controller.
Route::post('/get/card',[CardController::class,'getCardList'])->name('card.list');
public function getCardList(Request $request){
$treeItemID = $request->treeItemID;
return $treeItemID;
}
Scenario 2 => If you do want to hide some parameter inside the request then you can use GET type of request where use can pass data in url and get from request or get from parameter url inside in controller.
Route::get('/get/card/{treeItemID}',[CardController::class,'getCardList'])->name('card.list');
public function getCardList($treeItemID){
$treeItemID = $treeItemID;
return $treeItemID;
}
I am work with Laravel 5 and have implemented a working Restful API. I am trying to allow posts to be created by passing in an array like this...
post
title
excerpt
content
image
post
title
excerpt
content
image
The API currently works great for posting one individual post but how can I handle the array of posts instead?
Does anyone have an example I can see?
If you are using the Resource Controller, you should have a PostsController with a method store(). I am assuming your request payload is some JSON like this:
{"posts": [{"title":"foo"},{"title":"bar"}, …]}
So you need to json_decode the input. Then pass it to your database:
public function store()
{
$posts = json_decode($request->input('posts', ''));
if (is_array($posts)) {
DB::table('posts')->insert($posts);
}
}
There is probably some plugin or middleware or whatever to automatically decode the JSON payload. But apart from that, there is nothing special about doing what you ask for.
If you don't want to use the store() method (because it already stores a single Post or something) you can just add another route for your multiple Posts.
did you try to send JSON in the body? Here is a link with an example
Request body could look like the following:
{
"parameters":[
{
"value":{
"array":{
"elements":[
{
"string":{
"value":"value1"
}
},
{
"string":{
"value":"value2"
}
},
{
"string":{
"value":"value3"
}
}
]
}
},
"type":"Array/string",
"name":"arrayvariable"
}
]
}
This will convert the array every time you get it from the DB and every time you save it to the DB.
And here is an example using laravel casting link
Use attribute casting. Open your IdModel model and add this:
protected $casts = [
'id' => 'array' ];
I can not get values sent from post method, using http request.
I am getting values using get method, but I need to get it using post method.
I am not using any view, I want to call http url, and send some data in my controller using post method.
This is how my controller looks like,
namespace Spaarg\eMenuApi\Controller\Index;
class Products extends \Magento\Framework\App\Action\Action
{
public function __construct(\Magento\Framework\App\Action\Context $context)
{
return parent::__construct($context);
}
public function execute()
{
//$token = $this->getRequest()->getPostValue();
$token = $this->getRequest()->getPost();
}
}
I am new to magento 2, and I don't understand what is the problem.
It will be great if someone can help.
It probably has to do with the Content-type of the http request, where Magento only understands Json and Xml (this is explained here). If you're using a different Content-type in the request or your data doesn't match the type declared in the header, then getPost() will not work.
As a fallback, you can always get all the POST data by using the following way:
public function execute()
{
$postData = file_get_contents("php://input");
}
Keep in mind that this will get the raw string, so you will likely need to process it accordingly before using it (for example with json_decode() or something like that).
For more information about this, check this SO question.
In my controller i used this way. i want to pass a variable data to my index function of the controller through redirect
$in=1;
redirect(base_url()."home/index/".$in);
and my index function is
function index($in)
{
if($in==1)
{
}
}
But I'm getting some errors like undefined variables.
How can i solve this?
Use session to pass data while redirecting. There are a special method in CodeIgniter to do it called "set_flashdata"
$this->session->set_flashdata('in',1);
redirect("home/index");
Now you may get in at index controller like
function index()
{
$in = $this->session->flashdata('in');
if($in==1)
{
}
}
Remember this data will available only for redirect and lost on next page request. If you need stable data then you can use URL with parameter & GET $this->input->get('param1')
So in the controller you can have in one function :
$in=1;
redirect(base_url()."home/index/".$in);
And in the target function you can access the $in value like this :
$in = $this->uri->segment(3);
if(!is_numeric($in))
{
redirect();
}else{
if($in == 1){
}
}
I put segment(3) because on your example $in is after 2 dashes. But if you have for example this link structure : www.mydomain.com/subdomain/home/index/$in you'll have to use segment(4).
Hope that helps.
Use session to pass data while redirecting.There are two steps
Step 1 (Post Function):
$id = $_POST['id'];
$this->session->set_flashdata('data_name', $id);
redirect('login/form', 'refresh');
Step2 (Redirect Function):
$id_value = $this->session->flashdata('data_name');
If you want to complicate things, here's how:
On your routes.php file under application/config/routes.php, insert the code:
$route['home/index/(:any)'] = 'My_Controller/index/$1';
Then on your controller [My_Controller], do:
function index($in){
if($in==1)
{
...
}
}
Finally, pass any value with redirect:
$in=1;
redirect(base_url()."home/index/".$in);
Keep up the good work!
I appreciate that this is Codeigniter 3 question, but now in 2021 we have Codeigniter 4 and so I hope this will help anyone wondering the same.
CI4 has a new redirect function (which works differently to CI3 and so is not a like for like re-use) but actually comes with the withInput() function which does exactly what is needed.
So to redirect to any URL (non named-routed) you would use:
return redirect()->to($to)->withInput();
In your controller - I emphasise because it cannot be called from libraries or other places.
In the function where you are expecting old data you can helpfully use the new old() function. So if you had a key in your original post of FooBar then you could call old('FooBar'). old() is useful because it also escapes data by default.
If however, like me, you want to see the whole post then old() isn't helpful as the key is required. In that instance (and a bit of a cheat) you can do this instead:
print'<pre>';print_r($_SESSION['_ci_old_input']['post']);print'</pre>';
CI4 uses the same flash data methods behind the scenes that were given in the above answers and so we can just pull out the relevant session data.
To then escape the data simply wrap it in the new esc() function.
More info would be very helpful, as this should be working.
Things you can check:
Is your controller named home.php? Going to redirect(base_url()."home"); shows your home page?
Make your index function public.
public function index($in) {
....
}
My code is as follows:
$.getJSON("http://xx.xx.x.x/directory/index.php?c=json&m=get_listing&jsoncallback=?", { action:'listings' }, function(data) {
// code
});
This works just fine. But now I'm having a lot of troubles with other libraries that don't play friendly with query strings being enabled. If I turn query strings off, and change the URL above to:
http://xx.xx.x.x/directory/index.php/json/get_listing/jsoncallback=?
Doesn't work. Any ideas on a work around?
EDIT:
When I turn off query string, and use this:
http://xx.xx.x.x/directory/index.php/json/get_listing/jsoncallback=?
Safari's console shows the following error:
GET http://xx.xx.x.x/directory/index.php/json/get_listing/jsoncallback=jQuery17102770626428537071_1329431463691?action=categories&_=1329431463695 400 (Bad Request)
Fixed it. This works:
http://xxx.xx.x.x/directory/index.php/json/get_categories/?jsoncallback=?
If the last segment is for instance 7, the url must be composed as:
http://xx.xx.x.x/directory/index.php/json/get_listing/jsoncallback/7
Is someone still interested in this?
I just made a test on my website to combine Angular, Jsonp and CodeIgniter and it works great.
But i'm concerned by the security implications. If someone have a recommendation on this i will be grateful
Instead of sendig the paramteres directly to the controller url as here:
public function getObjectJson($page=null,$limit=null,$search=null){
if($page==null||$page<1){
$page=1;
}
if($limit==null||$limit<1){
$limit=10;
}
$objects=$this->Objects_model->getObjectsJson($page,$limit,$search);
echo $objects;
}
Send them in the url as a query and get them with the respective method in the controller:
public function getObjectsJsonp(){
$page=$this->input->get('page');
if($page==null||$page<1){
$page=1;
}
$limit=$this->input->get('limit');
if($limit==null||$limit<1){
$limit=10;
}
$search=$this->input->get('search');
$objects=$this->Objects_model->getObjectsJson($page,$limit,$search);
$var=$this->input->get('json_objectCallback');
echo $var.$objects;
}
And in my Angular factory the URL string is set as a query
objectsApp.factory('objectsFactory', ['$http',function($http) {
return {
getObjectsP: function(p1,p2,p3) {
//The callback function is harcoded and the prarmeters comes from the angular controller
return $http.jsonp("<?=base_url()?>Objects/getObjectsJsonp/?callback=json_objectCallback&page="+p1+"&limit="+p2+"&search="+p3).then(function(result) {
objects = result.data;
console.log(objects);
return objects;
});
}
}]);
Hope it helps.