Laravel GET Method not sending raw JSON in Server - laravel

Working with REST API's in Laravel. Can't send raw json request in body using GET method, it returns null values in my server environment. But in local server works fine. Refer the attached images. And my controller code was,
public function slots(Request $request)
{ //return $request->all();
$consult_rule = TRUE;
date_default_timezone_set('Asia/kolkata');
$current_time = date('H:i:s');
$curr_date = date('Y-m-d');
// $appoint_date = DateTime::createFromFormat('d/m/Y', $request->appoint_date)->format('Y-m-d');
// $appoint_date_format = strtotime($appoint_date);
// $appoint_day = date('l', $appoint_date_format);
$date = $request->appoint_date;
$doctor_id = $request->doctor_id;
$appoint_for = $request->appoint_for;
return $this->sendResponse(['doctor_id' => $doctor_id,'appoint_date' => $date,'appoint_for' => $appoint_for], 'Data retrieved successfully.');
}
And the images,
For Local server works fine
Localhost response
For Server works fine with Key Parameters
Server response with key parameters
For Server return null values with raw JSON parameters
response with raw JSON parameters

Since it is a GET route, it expects parameters in URL.
For POST request, you need to define a separate Route and function which will take parameters in body.
EDIT: you can't send parameters in body when using GET HTTP method.
Refer:
https://laravel.com/docs/7.x/routing#required-parameters

Related

Cannot send file from Postman to Laravel API

I am trying to send an image to my laravel APIs from postman.
I added the file(280KB) on the request body like so:
On the server side I am trying to catch the file and save it, but it returns that there is no file.
public function uploadImage(Request $request)
{
//returns false
$request->hasFile('profile_image');
//returns profile_image is required
$request->validate(['profile_image' => 'required|image:jpeg,png,jpg,gif,svg']);
//returns null
$request->file('profile_image');
}
I am calling the function from api.php like so:
Route::put('/creators/{id}/upload_image',[CreatorController::class,'uploadImage']);
I thought maybe I shouldn't put the file in Body, but couldn't find an alternative.
Also I am finally trying to send the file from a vue client, but I had the same Issue when trying to send the file from there.
How do I get the server to catch the file?
Edit: adjusted typo in example code
new code sample
I changed the method from put to post, since I wanted to test the post method as well. I also tried _method put in postman beforehand.
Here is the code sample on Laravel:
//api.php
Route::put('/creators/{id}/upload_image',[CreatorController::class,'uploadImage']);
//CreatorController.php
public function uploadImage(Request $request)
{
if($request->hasFile('profile_image')){
$allowedfileExtension=['gif','jpg','png'];
$file = $request->file('profile_image');
$extension = $file->getClientOriginalExtension();
if(in_array($extension,$allowedfileExtension)) {
$path = $file->store('public/images/profile');
$path_url = $path;
return ["image_url" => $path_url, "image" => $request->file('profile_image')];
}
return false;
}
}
The $request->hasFile('profile_image') returns true, but then $request->file('profile_image') returns null, failing to save the image.
My vue client side code (if it might turn useful):
if(this.profile_image != null){
let data = new FormData();
data.append('profile_image', this.profile_image)
axios
.post('http://localhost:8000/api/creators/'+uid+'/upload_image', data, head)
.then(
response => (
//successfully receives the image_url
this.creatorData.image_url = response.data.image_url,
console.log(response.data)
),
)
.catch(
error => (
localStorage.setItem('error', error),
console.log(error.response)
),
this.loading = false,
)
}
The client side actually receives the "image_url" but the image is not saved on laravel.
laravel dose not support put method directly.
you must use post method then pass _method to your laravel project
like this picture

update image in laravel 8 - API

I tried update my image, but it isn´t update.
I have the method upload , it works in a store method
private function upload($image)
{
$path_info = pathinfo($image->getClientOriginalName());`
$post_path = 'images/post';
$rename = uniqid() . '.' . $path_info['extension'];
$image->move(public_path() . "/$post_path", $rename);
return "$post_path/$rename";
}
I tried update the new image, but the message update successfully apears but not update
public function update(Request $request, Car $car)
{
if (!empty($request->file('image_url'))) {
$url_image = $this->upload($request->file('image_url'));
$car->image_url = $url_image;
}
$res = $car->save();
if ($res) {
return response()->json(['message' => 'Car update succesfully']);
}
return response()->json(['message' => 'Error to update car'], 500);
}
La actualización es correcta pero en la BDD no actualiza
Imagen de actualización con POSTMAN
Try changing the method in postman to POST and add this query string parameter to the URL: its name is _method and the value is PUT.
Your API consumers will call the endpoint in this way but you will keep the route definition with the PUT verb. Read more about it here
The request PUT doesnt have a body like the method POST as of the RFCs (Something with the Content-Length, dont remember correctly).
Even if your API can handle PUT methods with body, your postman will try to send the file in the query field (URL) and that will mostly break the file. You can check the URL called by postman in the request Headers.
Laravel has a workaround for this, you send the parameter _method=PUT in a POST request and the router will handle it as a PUT request (if you declared it so).

Cannot send HTML string through axios

I'm working on a blog like website and have being adding this rich text editor feature to it. This app is built with Vue for the front and Laravel, and this text editor is a dependency called vue-quill.
I use axios to post all the data and nothing more. Im using it to create posts with Raw html tags from this editor, it actually works fine creating and updating posts locally, but only fails on my server whenever you try to update any post, it returns empty response and status 200.
It does not happen when you create a post. Im not using any kind of image upload service but I'm using my own solution, which consists on transforming images from base 64 to file objects and then send them to a controller via axios. On update action it is similar but the images that were already uploaded on the post are fetched, then converted to base64 again and then converted to file objects again (in order to preserve previous images) for new images I convert them from base64 to file object as I do on my create action.
Here is the code I use to create from base 64 to file object :
dataURLtoFile(dataurl, filename) {
let arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while(n--){
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], filename, {type:mime});
}
And this would be my axios action:
axios
.post("/api/posts", formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
.then((response)=>{
this.submit = false;
this.title= '';
this.showAlert("success", 'Post created successfully.' , '')
})
.catch((error) =>{
// etc
});
The formData object only store the raw html, images and a string, nothing more than that, but I'm not sure if the headers of the axios are ok, the laravel action is like this:
public function updatePost(Request $request)
{
$request->validate([
'files.*' => 'required|mimes:jpg,jpeg,png|max:2048'
]);
$post = Post::find($request->postId);
$images = $request->file('files');
// creamos el post primero
$post->title = $request->title;
$post->body = $request->body;
$post->save();
// the rest of the code for storing images
return response()->json(['post' => $post]);
I think something is preventing it to reach to this action, because the response is empty.
Edit: I had a problem later where the request was giving status 301, after searching here and there I found out that everything was okay but in the server. The host has to be configured as stated here in this quick guide for 301 troubles : https://medium.com/#mshanak/laravel-return-empty-response-690f8a308d9a.

laravel api without respond

I have a issue, after i eliminate cors policy on laravel i sending some json data to check respond. But nothing happens...
I sending request by axios using react.js, i sending json data collected from state.
and now i trying to collect that data by laravel, but that is hardest patch.
already try something like that:
$content='test';
return Response::$content;
or just echo 'test' but nothing comes...
My code is inside controller.
class testRequest extends Controller
{
public function show(Request $request)
{
//$data = $request->json()->all();
// $experience = $data->experience;
$content='test';
return Response::$content;
}
}
for now i expect to get respond like 'test' but after that i will need to send a link to file path for respond.
the Response::$content is just wrong... the :: operator is used to access static member functions or attributes of the Response class... you should do something like this:
return Response::json(['test' => $content]);
or
return response()->json(['test' => $content]);
in order to respond with a JSON document.

How can I set a response using a var?

In the laravel docs it has:
return response($content);
What format is $content?
I want to return it via a var like so:
$res = [null, 204];
return response($res);
But the above fails, just returns a 200.
How can I set a response using a var?
response method like this. response($contents, $statusCode) It's a method of instance Response Object. as you can see that method is getting two parameters. one is contents that you are trying to return to client side. it depending what Content-Type is set in header.
so you can try like this.
$contents = "something whatever";
$statusCode = 204;
return response($contents, $statusCode);
$content can be various things - null, a string, an array.
Status codes are set via a second parameter, not an array element. Passing it an array results in a JSON response, so you're creating a 200 status JSON response of [null,204] with your code.
You fundamentally need to do:
return response(null, 204);
What you can potentially do is generate a response as a variable:
$res = response(null, 204);
and then return $res; elsewhere.

Resources