Cannot upload file using guzzle and send to laravel API - laravel

I have two laravel projects, one for API and one for front end. What I want to achieve is to send the uploaded file on my front end and send it to my API using guzzlehttp6. Here's my code.
FrontEnd Laravel:
public function store(Request $request, $module_id)
{
$videos = $request->file('file');
// $name = time().$videos->getClientOriginalName();
// $path = ('videos');
// $videoFinal = $videos->move($path, $name);
$file_name = fopen($videos, 'r');
$client = new Client(['base_uri' => 'http://localhost/api.kourse/public/api/v1/']);
try{
$response = $client->request('POST', 'modules/'.$module_id.'/videos',[
'file_name' => $file_name
]);
}catch(ClientException $e){
return $e->getResponse();
}
}
When returning the $videos im getting the path of the file.
Here's my API
public function store(VideoRequest $request, $moduleId)
{
$module = Module::find($moduleId);
if( !$module )
{
return response()->json([
'message' => 'Module does not exist',
'code' => 404
],404);
}
$file = $request->file('file_name');
$name = time(). $file->getClientOriginalName();
$path = '/videos';
$file->move(public_path().$path, $name);
Video::create([
'file_name' => $name,
'file_path' => $path.$name,
'module_id' => $module->id
]);
return response()->json([
'message' => 'Successfully created and assgin video to this module'
],200);
}
What Iam getting is that :
{message: {file_name: ["The file name field is required."]}, code: 422}
code
:
422
as defined in my VideoRequest.
Can anyone help me on this.

Related

how to send multiple files with one key in laravel using guzzle Http

I can send multiple files and string data with post man like bellow:
but the question is how to send similar request with laravel http ?
what I did is :
public function performMultiPartRequest($requestUrl, $body)
{
$response = Http::withHeaders(['Accept' => 'application/json']);
$data = [];
foreach ($body as $key => $value) {
if (gettype($value) == 'string') // for string data. works well.
array_push($data,[$key, $value]);
else if (gettype($value) == 'array') { // array of files. doesn't work!
foreach ($value as $file) {
$extension = $file->getClientOriginalExtension();
$response->attach($key , fopen($file, 'r'), mt_rand(100,1000).".".$extension);
}
}
else { // one file. works well.
$extension = $value->getClientOriginalExtension();
$response->attach($key, fopen($value, 'r'), 'temp.'.$extension);
}
}
$response = $response->post($this->baseUri.$requestUrl, $body);
return $response;
}
when I try to send some string key value with a file or files with different keys, it's ok, but when I try to send data with multiple file upload (one key) error happens.
the error message is:
A 'contents' key is required with status code 0
unfortunately I didn't find a solution to do the job with Illuminate\Support\Facades\Http yet, but because of time limitation of the project, I used GuzzleHttp\Client instead:
$client = new Client([
"base_uri" => $url,
]);
$data = [];
$data['multipart'] = [];
foreach ($body as $key => $value) {
if (gettype($value) == 'string') {
array_push($data['multipart'], [
'name' => $key,
'contents' => $value
]);
} else if (gettype($value) == 'array') {
foreach ($value as $k => $file) {
if (file_exists($file)) {
$extension = $file->getClientOriginalExtension();
array_push($data['multipart'], [
'name' => $key."[]",
'contents' => fopen($file, 'r'),
'filename' => mt_rand(100, 1000) . "." . $extension
]);
}
}
}
}
$response = $client->request('POST', $requestUrl, $data);
it works fine for my case.
but any solution to laravel Http facade will be appreciated for this problem.

uploading image and got error in laravel "Undefined variable: data"

I am trying to update the product and for that I am updating the pictures. I meant if user want to add more pictures to it but when I do this I get below error
Undefined variable: data
Also I want to restrict the total uploading pictures to max 3 pictures or 2 pictures and 1 video
When I add a video it does not show like it does not play
Any help would be great. Thank for the help in advance
public function editProduct($id, Request $request) {
if(Auth::check()) {
$pn = Input::get('pn');
$desc = Input::get('desc');
$price = Input::get('price');
// $products = Product::all();
$products = Product::where('id', $id)->first();
// foreach($products as $p) {
if(($products->user_id == Auth::user()->id) && ($products->id == $id)) {
$this->validate($request, [
'filename.*' => 'required|max:5000',
// 'filename.*' => 'image|mimes:jpeg,png,jpg,mp4|max:5000'
]);
if($request->hasfile('filename'))
{
foreach($request->file('filename') as $image)
{
$name = $image->getClientOriginalName();
$filename = time(). '-' . $image;
$file_path = $image->move(public_path().'/assets/images/', $name);
$data[] = $name;
}
}
$new_name = json_encode($data);
$products = Product::where('user_id', Auth::user()->id)
->where('id', $id)->update([
'product_name' => $pn,
'description' => $desc,
'price' => $price,
'filename' => $new_name,
]);
}
} else {
Session::flash("message", "OOPS! You dont have permission to edit the items. Please login first.");
return redirect("/register-user");
}
I was missing enctype="multipart/form-data" files=true in my form in the view so it was not getting a file from the blade so got it fixed now

Send pdf file as email attachment in laravel 5.7

I want to send email of invoice blade file as pdf but i getting following error
(1/1) Swift_IoException
Unable to open file for reading [/storage/D:\xampp\htdocs\clientreq\public/mypdf.pdf]
controller:
public function insert(Request $req)
{
ini_set('max_execution_time', 300000);
$mytime = Carbon::now();
$project_type=implode(',',$req->input('project_type'));
//$qty=implode(',',$req->input('qty'));
$amount=implode(',',$req->input('amount'));
$id=$req->input('id');
$bill_date=$req->input('bill_date');
$updated_at=$mytime->toDateTimeString();
$created_at=$mytime->toDateTimeString();
$data = array('client_id'=>$id,'date_of_bill'=>$bill_date,'description'=>$project_type,'amount'=>$amount,'created_at' => $created_at,'updated_at' => $updated_at);
DB::table('bill')->insert($data);
$client = DB::table('requirement')
->join('bill','requirement.id','=','bill.client_id')
->select('requirement.*','bill.*')
->where('requirement.id',$id)
->where('bill.date_of_bill',$bill_date)
->first();
$data = array(
'client_name' => $client->client_name,
'company_name' => $client->company_name,
);
$pdf = \PDF::loadView('pages.invoice',$data);
//return $pdf->stream();
$data = array(
'email_address'=>'seemashelar01#gmail.com',
);
Mail::send('pages.invoice', $data, function($message) use($data) {
$message->from('seemashelar01#gmail.com', 'PuraBox');
$message->to($data['email_address']);
$message->subject('hello');
$filename = \Storage::url(public_path() . '/' . 'mypdf.pdf');
$message->attach($filename);
//Full path with the pdf name
});
}
if you want address file from Storage you should call attachFromStorage , like this:
$message->attachFromStorage(
/path/to/file',
'name.pdf', [
'mime' => 'application/pdf'
]);
more info : https://laravel.com/docs/5.7/mail#attachments
Try this bellow example thats it
$data = array(
'name' => Input::get('name'),
'detail'=>Input::get('detail'),
'sender' => Input::get('sender')
);
$pdf = PDF::loadView('letters.test', $data);
Mail::send('emails.invoice', $data, function($message) use($pdf)
{
$message->from('us#example.com', 'Your Name');
$message->to('foo#example.com')->subject('Invoice');
$message->attachData($pdf->output(), "invoice.pdf");
});

Save image to database

I want to save image name to database but it always save to C:\xampp\tmp\phpAB3A.tmp. btw im not using xampp, im using laragon.How to change the path? i want to save to storage/app/public
'name'=> 'required',
'email' => 'required',
//'logo' => 'required',
$imageName = time().'.'.request()->logo->getClientOriginalExtension();
request()->logo->move(storage_path('app/public'), $imageName);
Company::create($request->all());
return redirect()->route('company.dashboard')->with('Success');
In your Company::create you have to define the path... Something like:Company::create([
'path' => torage_path('app/public',$imageName),....]);
I'm using laravel 5.8 and this code worked for me.
In controller
<?php
public function store()
{
// I did like this, because storeLogo method is reusable
$data = request()->validate([ /* ... */ ]);
$company = Company::create($data);
$this->storeLogo($company);
// but you can do like this
$data = request()->validate([ /* ... */ ]);
if (request()->has('logo')) {
$data['logo'] = request()->logo->store('', 'public');
}
$company = Company::create($data);
}
private function storeLogo(Company $company)
{
if (request()->has('logo')) {
$company->update([
'logo' => request()->logo->store('', 'public'),
// logo file is stored at /storage/app/public/
]);
}
}
$input = $request->all();
$fileName = '';
if ($request->hasFile('logo')) {
$destinationPath = storage_path('app/public');
$file = $request->logo;
$fileName = time() . '.'.$file->clientExtension();
$file->move($destinationPath, $fileName);
}
$input['logo'] = $fileName;
Company::create($input);

Laravel user post image upload error

I have error while i am uploading Post Image I can save picture on my computer but in my database filename is distorted.
Here is my PostsController
public function store(Request $request, User $user, Image $image)
{
$this->validate($request, [
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
'body' => 'required'
]);
if( $request->hasFile('image') ) {
$image = $request->file('image');
$filename = time() . '.' . $image->getClientOriginalExtension();
Image::make($image)->save( public_path('uploads/images/' . $filename ) );
}
$image = $filename;
auth()->user()->publish(
new Post(request(['body', 'image'])));
return redirect('/');
}
The problem is that you try to insert the wrong variable into your database table. So, improve your code like this:
auth()->user()->publish(
new Post(['photo' => request('body'), 'image' => $image])
);

Resources