Sending an image with HTTP POST - laravel

Recently I wanted to separate my project in different services to I wanted to make blogs independent from the project.
In the first project i have written this code. I want to send the data that i get from the form to another API http://127.0.0.1:100/api/saveBlog
public function update(Request $request, $blog)
{
if (!$blog instanceof Blog) {
$blog = $this->getById($blog);
}
$response = Http::post("http://127.0.0.1:100/api/saveBlog",[
'name' => $request->input('name'),
'description' => $request->input('description'),
'name' => $request->input('name'),
'photto' => $request->file('photto')
]);
dd($response->status());
}
In the API service i am trying to read the data
Route::post("/saveBlog",function (Request $request){
$blog = new Blog();
$blog->name = $request->input('name');
$blog->description = $request->input('description');
$blog->name = $request->input('name');
$main = $request->file('photto');
$fileName = microtime() . '.' . $main->getClientOriginalExtension();
$img = Image::make($main->getRealPath());
$img->resize(400, 400);
$img->stream();
Storage::disk('local')->put('public/blogs/' . $fileName, $img, 'public');
$blog->image_path = "/storage/blogs/" . $fileName;
return $blog->save();
});
But i am getting 500 status error and blog is not being saved in database.
I think the problem is with $request->file('photto')
ANY IDEA?

check whether image exist in request like below
if($request->has('photto')){
$main = $request->file('photto');
$fileName = microtime() . '.' . $main->getClientOriginalExtension();
$img = Image::make($main->getRealPath());
$img->resize(400, 400);
$img->stream();
Storage::disk('local')->put('public/blogs/' . $fileName, $img, 'public');
$blog->image_path = "/storage/blogs/" . $fileName;
}
Updates
$photo = fopen(public_path('/storage/filename'), 'r');
$response = Http::
attach('photo', $photo)
->post($url, [
'param_1' => 'param_1 contents',
...
]);

Related

image not store in database laravel

I want to Create app in laravel that manage my events
i use this code for EventController
public function store(Request $request)
{
$request->validate([
'inviter'=>'max:255',
'date'=>'max:255',
'phone'=>'max:255',
'whatsapp'=>'max:255',
'location'=>'max:255',
'approval'=>'max:255',
'number'=>'max:255',
'description'=>'max:255',
'track'=>'max:255',
]);
$eve = new Event([
'inviter'=> $request->get('inviter'),
'date'=> $request->get('date'),
'phone'=> $request->get('phone'),
'whatsapp'=> $request->get('whatsapp'),
'location'=> $request->get('location'),
'number'=> $request->get('number'),
'approval'=> $request->get('approval'),
'description'=> $request->get('description'),
'track'=> $request->get('track'),
]);
if ($request->hasFile('file')) {
$file = $request->file('file');
$fileName = $file->getClientOriginalName();
$filePath = time() . '.' . $file->getClientOriginalName();
$request->file->move(public_path('uploads/events'), $filePath);
$eventImage = Image::createNew();
$eventImage->filename_path = $filePath;
$eventImage->original_filename = $fileName;
$eventImage->event_id = $eve->id;
$eventImage->save();
}
return redirect(route('event.index'))->with('success','Event Created');
}
but image dont create I think related to event_id when I was testing the code correctly and incorrectly
Try this
$eve = Event::create([
'inviter'=> $request->get('inviter'),
'date'=> $request->get('date'),
'phone'=> $request->get('phone'),
'whatsapp'=> $request->get('whatsapp'),
'location'=> $request->get('location'),
'number'=> $request->get('number'),
'approval'=> $request->get('approval'),
'description'=> $request->get('description'),
'track'=> $request->get('track'),
]);

send file to an api using guzzle http client

after uploading an image in web system a i want to push the image to another web system b.i am using guzzle http client to push and save the image in system b.i have been able to save the image in system a but when it reaches the part to push and save to system b an error that i have set to show when there is an error on uploading the image.here is my function to save the image on system a
public function productSavePicture(Request $request)
{
try {
$validation = Validator::make($request->all(), [
'product_id' => 'required',
]);
if ($validation->fails()) {
throw new \Exception("validation_error", 19);
}
$product_details = product::where('systemid', $request->product_id)->first();
if (!$product_details) {
throw new \Exception('product_not_found', 25);
}
if ($request->hasfile('file')) {
$file = $request->file('file');
$extension = $file->getClientOriginalExtension(); // getting image extension
$company_id = Auth::user()->staff->company_id;
if (!in_array($extension, array(
'jpg', 'JPG', 'png', 'PNG', 'jpeg', 'JPEG', 'gif', 'GIF', 'bmp', 'BMP', 'tiff', 'TIFF'))) {
return abort(403);
}
$filename = ('p' . sprintf("%010d", $product_details->id)) . '-m' . sprintf("%010d", $company_id) . rand(1000, 9999) . '.' . $extension;
$product_id = $product_details->id;
$this->check_location("/images/product/$product_id/");
$file->move(public_path() . ("/images/product/$product_id/"), $filename);
$this->check_location("/images/product/$product_id/thumb/");
$thumb = new thumb();
$dest = public_path() . "/images/product/$product_id/thumb/thumb_" . $filename;
$thumb->createThumbnail(
public_path() . "/images/product/$product_id/" . $filename,
$dest,
200);
$systemid = $request->product_id;
$product_details->photo_1 = $filename;
$product_details->thumbnail_1 = 'thumb_' . $filename;
$product_details->save();
// push image to system on saving
$client = new \GuzzleHttp\Client();
$url = "http://systemb/api/push_image";
$response = $client->request('POST',$url,[
'headers' => [ ],
'multipart' => [
[
'name' => $filename,
'contents' => file_get_contents($product_details->getPath()),
],
],
]);
} else {
return abort(403);
}
} catch (\Exception $e) {
if ($e->getMessage() == 'validation_error') {
return '';
}
if ($e->getMessage() == 'product_not_found') {
$msg = "Error occured while uploading, Invalid product selected";
}
{
$msg = "Error occured while uploading picture";
}
$data = view('layouts.dialog', compact('msg'));
}
return $data;
}
i am getting the error "Error occured while uploading picture" but the error is saved in systema but its unabe to be pushed in systemb..i havent understood where i have gone wrong with my code base but i guess that part on guzzle isnt being executed because the data is being saved in systema but its unable to be pushed to systemb.what might be the issue here
Your class Product doesnt have the method getPath() declared
file_get_contents($product_details->getPath())
Change it so it uses the path you used above that line
file_get_contents(public_path() . "/images/product/$product_id/".$filename)

Laravel I try to duplicate an object and add pictures in each object

I have a room to add. And there are fields called pieces. If the user has written all the fields, he chose pictures for the room. and wrote 5 pieces. I want to add 5 pieces to the same room with selected fields and photos. That is, duplicate the same object in several pieces.
RoomController store function
public function store(Request $request)
{
$request->validate([
'title.*' => 'required',
'content.*' => 'required',
'people' => 'required',
'hotel_id' => 'required',
'night_price' => 'required',
'pieces' => 'required',
'single_bed' => 'required',
'double_bed' => 'required',
'roomImages' => 'required',
'roomImages.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'
]);
$rooms = array_fill(1, $request->get('pieces'), $request->all());
foreach ($rooms as $room){
dd($rooms);
$obj = new Room();
// Set translations
$obj->setTranslations('title', $room['title']);
$obj->setTranslations('content', $room['content']);
// Save object
$obj->amenities = $room['amenities'];
$obj->fill($room);
$obj->save();
foreach ($room['roomImages'] as $file) {
$file_name = time() . '_' . md5($file->getClientOriginalName()) . '.' . $file->getClientOriginalExtension();
$file->move(public_path('/uploads/rooms/'), $file_name);
// Save image in Model Image
$file = new Image();
$file->src = $file_name;
$obj->file()->save($file);
}
}
return redirect()->route('rooms.index');
}
Error
One circle of the foreach is running, the object with the pictures is added. On the 2nd lap, the foreach stops and shows this error
Try the bellow code
foreach ($request->roomImages as $file) {
$file_name = time() . '_' . md5($file->getClientOriginalName()) . '.' . $file->getClientOriginalExtension();
$file->move(public_path('/uploads/rooms/'), $file_name);
}
$rooms = array_fill(1, $request->get('pieces'), $request->all());
foreach ($rooms as $key => $room){
$obj = new Room();
// Set translations
$obj->setTranslations('title', $room['title']);
$obj->setTranslations('content', $room['content']);
// Save object
$obj->amenities = $room['amenities'];
$obj->fill($room);
$obj->save();
\File::copy(public_path('/uploads/rooms/'.$file_name), public_path('/uploads/rooms/'.$key.$file_name));
$file = new Image();
$file->src = $key.$file_name;
$obj->file()->save($file);
}
\File::delete(public_path('/uploads/rooms/'.$file_name));
The move function will delete the file from the original request. So when the loop run second time, you are getting error.
So your issue looks like you are overriding $file when creating your Image model.
foreach ($room['roomImages'] as $file) {
$file_name = time() . '_' . md5($file->getClientOriginalName()) . '.' . $file->getClientOriginalExtension();
$file->move(public_path('/uploads/rooms/'), $file_name);
// Save image in Model Image
// Updated variable name
$image = new Image();
$image->src = $file_name;
// save Model
$image->save();
$obj->file()->save($file);
}

updated image stores in database but not folder in laravel

problem is that company_photo stores in database but not store in company_photos folder, please tell me where i going wrong..
public function update(Request $request, Company $company,CompanyOtherInfo $CompanyOtherInfo )
{
//dd($company);
//dd(request()->all());
if($request->hasFile('company_photo')){
$files=public_path().'/company_photos/'.$req->input('company_photo1');
File::delete($files);
//dd($files);
$file = $req->file('company_photo');
$destinationPath = public_path().'/company_photos/';
$filename = $file->getClientOriginalName();
$file->move($destinationPath, $filename);
// echo $filename;
}
else{
$filename=$request->input('company_photo1');
}
//dd($request);
//dd($filename);
$company::where('companies.company_id',$company->company_id)
->update([
'company_photo' => $filename,
'company_name' => request('company_name'),
'company_email' => request('company_email'),
'company_mobile' => request('company_mobile'),
'company_country' => request('company_country'),
'company_state' => request('company_state'),
'company_city' => request('company_city'),
'company_pincode' => request('company_pincode'),
'company_address' => request('company_address'),
'industry_id' => request('industry_id'),
'segment_id' => request('segment_id'),
'company_code' => request('company_code'),
'contact_person'=>request('contact_person'),
]);
The issue you had is you changed the variable $request to $req half way through your code:
Change these lines:
$files = public_path().'/company_photos/'.$req->input('company_photo1');
$file = $req->file('company_photo');
to:
$files = public_path().'/company_photos/'.$request->input('company_photo1');
$file = $request->file('company_photo');
Here is the code with a little refactor:
$filename = $request->input('company_photo1');
if ($request->hasFile('company_photo')) {
$files = public_path().'/company_photos/'.$fileName;
File::delete($files);
$file = $request->file('company_photo');
$file->move(public_path().'/company_photos/', $file->getClientOriginalName());
}

how to change laravel directory from storage/app/public to public/media

Please i want to change the default laravel configuration from storage/app/public to public/media on the server. In localhost it worked with storage:link but on the server it isn't working even after adding a symlink. Below is my symlink code.
<?php symlink('/home/cemo/cem/storage/app/public','/home/cemo/public_html');
Also if i return the public_path() from the store function i get /home/cemo/cem/public
this is the structure of my cpanel
below is my store function using image intervention
public function store(Request $request)
{
return public_path();
$this->validate($request,[
'title'=>'required|min:6',
'body'=>'required'
]);
if($request->hasFile('image')){
$img = $request->file('image');
$imgName = time().'-'.uniqid() . '.' . $img->getClientOriginalExtension();
}
else{
$imgName = 'default.jpg';
}
$posts = new post;
$posts->title = $request->title;
$posts->body = $request->body;
$posts->posted_by = $request->posted_by;
$posts->status = $request->status;
$posts->position = $request->position;
$posts->image = $imgName;
$posts->source = $request->source;
$posts->save();
$posts->tags()->sync($request->tags);
if(!empty($img)){
Image::make($img)->resize(1500,550)->save(public_path('/media/images/blog/'. $imgName));
}
$notification = array(
'message' => 'Successfully created',
'alert-type' => 'success'
);
return redirect(route('post.index'))->with($notification);
}
In config/filesystems.php
Change the array to:
'root' => 'public/media',

Resources