How to retrieve array of objects sent by Ajax in laravel - php

I am using Laravel with Vuejs and AXIOS for HTTP requests. I am sending a post request with the array of objects. So in my laravel store function how can I retrieve that data from the $request?
my questions array looks like:
data:{
questions:[{
question:'',
opt1:''
},
{
question:'',
opt1:''
}
]
}
Laravel Store method in controller:
public function store(Request $request)
{
return $request;
}
vue code:
axios.post('/addTest',this.$data.questions).then(response=>{
console.log(response.data);
});
in this code questions is an array of objects.

In Laravel you have a store method and then you returning the request?Why you are doing that?To see the request from frontend? If so then I recommend you to use postman for this.
Postman is easy to use and you can send a similar request that frontend sends.Then in laravel store function you can do
dd($request) //to output the request that postman sends
You said: how can I retrieve that data from the $request
If you send from frontend something like
{ id: 1 }
Then in laravel you can do
$id = $request->get('id');
Below you can see how i send a request with postman,and how output the request.
Your request with postman
Laravel code to output request
The response from Laravel displayed in postman

If the this.$data.questions is an array, you can simply use the input() method to pull all of the questions:
$questions = $request->input();
Let say you only want to pull the question property of the second item, you can do it like so in Laravel:
$secondQuestion = $request->input('1.question');
However, it would also be nice if you pass the questions as an object:
axios.post('/addTest', { questions: this.$data.questions });
And your PHP part will look like this:
$questions = $request->input('questions');
Hope this gives you some ideas.

Related

Getting parameters on Laravel from an Axios Post Request Body

Im currently working on a Laravel APP and one of the endpoints is a method that receives an Axios Post Request from a React APP with some parameters.
On laravel i only need to get those Post Resquest Parameters to save them on a database but im not figure how i get only the values.
Im using Postman to test it and im sending on the body a value '1234567890' with the value 'param', something like this:
axios.post("/myendpoint", {
param: '1234567890',
});
and on Laravel im doing this (as i've seen on another stackoverflow question):
public function myendpointmethod(Request $request)
{
return response()->json($request->param);
}
but this only returns me an empty array.
Im using Laravel Framework 7.25.0.
Thanks a lot

Laravel 5 API - Handle arrays

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

Laravel send data via request to another project

I have a laravel api controller where I'm getting data from a table.
public function moveData() {
$movelivesales = DB::table('st_sales_live')->get();
return $movelivesales;
}
I'm getting all the data, now how can I send this data to another project api(this api is ready) using request ? Any help please?
Just create a route like this to get your data($movelivesales):
Route::get('/your/path', 'YourController#moveData');
Then if you access:
http://yourdomain.com/your/path you will get a json of your data
You can get the data from api with php: file_get_contents('http://yourdomain.com/your/path');

Getting values sent using post method in controller in magento 2 api

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.

Slim PHP - Right way to use request and response objects

I'm new to Slim and PHP, but I'm trying to do a simple rest API with Slim. It's working, but I don't know if I'm doing it the right way and I cannot find another way to do it.
For example, I've a route like that:
$app->get('/contacts', '\Namespace\Class:method');
The method:
public function searchContacts($request, $response) {
return Contact::searchContacts($resquest, $response);
}
So, the unique way I found to access request and response from other classes is by passing the objects as params. Is it correct or is there a better (right) way to do it?
I think your way is not good.
Controller should process request and return response.
Your model(Contact) should'nt process requests. It should take needed params and return data.
Simple example:
public function searchContacts($request, $response)
{
// to example, you pass only name of contact
$results = Contact::searchContacts($request->get('contactName'));
$response->getBody()->write(json_encode($results));
return $response;
}
You don't need access to Request and Response objects from another classes. If it required, possible your architecture is wrong.
Good example from official site: http://www.slimframework.com/docs/tutorial/first-app.html#create-routes
the simplest way is to get the values from params and recieved the response in method.
$app->get('/contacts', function (Request $request, Response $response) {
$Contactname = $request->getAttribute('contact');
//You can put your search code here.
$response->getBody()->write("Contact name is, $name");
return $response;
});

Categories