Multiple upload using Laravel Storage - laravel

I was try to upload multiple files using Storage so here's my code:
public function store(Request $request)
{
$gallery = new Gallery();
$gallery->name = $request->name;
$gallery->description = $request->description;
$gallery->save();
$path = 'public'.'/'.str_slug($request->name);
Storage::makeDirectory(str_slug($request->name));
$image = new Image();
if ( is_array($request->images)) {
foreach ($request->images as $file) {
$image->gallery_id = $gallery->id;
$image->name = $file->getClientOriginalName();
$image->extension = $file->extension();
$image->save();
Storage::putFileAs($path, $file);
}
} else {
$image->gallery_id = $gallery->id;
$image->name = $request->images->getClientOriginalName();
$image->save();
}
}
and I already setup my form like this:
<div class="form-group">
<label for="images" class="col-md-2 control-label">Images</label>
<div class="col-md-6">
<input type="file" class="form-control" name="images[]" id="images[]" multiple>
</div>
</div>
it give me an errors like this:
"Type error: Too few arguments to function Illuminate\Filesystem\FilesystemAdapter::putFileAs(), 2 passed in E:\laragon\www\blog\vendor\laravel\framework\src\Illuminate\Filesystem\FilesystemManager.php on line 343 and at least 3 expected ◀"
so the problem is it the way I check that it has multiple file using is_array is right? and the second what can cause this problems?

Pass the 3rd argument to the putFileAs method
if( is_array($request->images)){
foreach ($request->images as $file) {
$image = new Image();
$image->gallery_id = $gallery->id;
$image->name = $file->getClientOriginalName();
$image->extension = $file->extension();
$image->size = 555;
$image->save();
// Or any custom name as the third argument
Storage::putFileAs($path, $file, $file->getClientOriginalName());
}
} else {
$image = new Image();
$image->gallery_id = $gallery->id;
$image->name = $request->images->getClientOriginalName();;
$image->save();
// Or any custom name as the third argument
Storage::putFileAs($path, $request->images, $request->images->getClientOriginalName());
}
return back();
Documentation

You can use below example. I think this will help you to solve your problem
public function store(Request $request)
{
$gallery = new Gallery();
$gallery->name = $request->name;
$gallery->description = $request->description;
$gallery->save();
$path = '/images/'.str_slug($request->name);
if( is_array($request->images)){
foreach ($request->images as $file){
$image = new Image();
$image->gallery_id = $gallery->id;
$image->name = $file->getClientOriginalName();
$image->extension = $file->extension();
$image->size = 555;
$image->save();
$file->move(public_path($path, $image->name);
}
}else{
$image = new Image();
$image->gallery_id = $gallery->id;
$image->name = $request->images->getClientOriginalName();;
$image->save();
$file->move(public_path($slug, $image->name);
}
return back();
}

The problem is clear. You are trying to call the function "putFileAs" using 2 parameters, when she needs at least 3.
Just take a look in the documentation here
So

Related

Save both original image and conversion to webp in laravel storage

I'm trying to save original jpg image and also a converted webp image to my storage when I'm storing images in my project.
public function store($data)
{
if (!$data->hasFile('fileName')) {
return response()->json(['upload_file_not_found'], 400);
}
$allowedfileExtension = ['jpg', 'jpeg'];
$files = $data->file('fileName');
$errors = [];
$images = [];
foreach ($data->fileName as $mediaFiles) {
$extension = $mediaFiles->getClientOriginalExtension();
$check = in_array($extension, $allowedfileExtension);
if ($check) {
// $path = $mediaFiles->store('public/images');
$name = $mediaFiles->getClientOriginalName();
//store image file into directory and db
$image = new Image();
$image->title = $name;
// $image->path = substr($path, 7);
$image->description = $data->description;
$image->author_id = $data->author_id;
$image->save();
//put image to storage wih unique folder
$path = $mediaFiles->storeAs('public/images/article-images/'.$image->id, $name);
//try to convert to webp and add to storage
$image = InterventionImage::make($mediaFiles)->encode('webp', 90)->resize(200, 250)->save('public/images/' . $name . '.webp');
//
//update images path in database
$image->update(['path' => substr($path, 7)]);
//add to attach the article id
if ($data->article_id) {
$image->articles()->attach($data->article_id);
}
array_push($images, $image);
} else {
return response()->json(['invalid_file_format'], 422);
}
}
return $images;
}
I'm using intervention library but when I try to save converted image to my storage I get the error "message": "Can't write image data to path (public/images/newimage.jpg.webp)",
can someone help with this or have any other suggestion how to do this?
if you want to convert image in to WEBP without any service or package, try this method. work for me. have any question can ask. Thankyou
$post = $request->all();
$file = #$post['file'];
$code = 200;
$extension = $file->getClientOriginalExtension();
$imageName = $file->getClientOriginalName();
$path = 'your_path';
if(!$file->move(public_path($path), $imageName)){
$code = 404;
}
if(in_array($extension,["jpeg","jpg","png"])){
//old image
$webp = public_path().'/'.$path.'/'.$imageName;
$im = imagecreatefromstring(file_get_contents($webp));
imagepalettetotruecolor($im);
// have exact value with WEBP extension
$new_webp = preg_replace('"\.(jpg|jpeg|png|webp)$"', '.webp', $webp);
// set qualityy according to requirement
return imagewebp($im, $new_webp, 50);
}
this will save JPG/PNG and WEBP file both to the move Folder.
If someone ever have the same problem I did it like this
public function newStore($data)
{
if (!$data->hasFile('fileName')) {
return response()->json(['upload_file_not_found'], 400);
}
$allowedfileExtension = ['jpg', 'jpeg'];
$files = $data->file('fileName');
$errors = [];
$images = [];
foreach ($data->fileName as $mediaFiles) {
$extension = $mediaFiles->getClientOriginalExtension();
$check = in_array($extension, $allowedfileExtension);
if ($check) {
// $path = $mediaFiles->store('public/images');
$name = $mediaFiles->getClientOriginalName();
//getting the name of the file without extension
$filename = pathinfo($name, PATHINFO_FILENAME);
//store image file into directory and db
$image = new Image();
$image->title = $name;
// $image->path = substr($path, 7);
$image->description = $data->description;
$image->author_id = $data->author_id;
$image->save();
//put image to storage in unique folder
$path = $mediaFiles->storeAs('public/images/article-images/' . $image->id, $name);
//imege conversion in webp format and move to right folder
$interventionImage = InterventionImage::make($mediaFiles)->stream("webp", 100);
Storage::disk('local')->put($filename . '.webp', $interventionImage, 'public');
Storage::move($filename . '.webp', 'public/images/article-images/' . $image->id . '/' . $filename . '.webp');
//update images path in database
$image->update(['path' => substr($path, 7)]);
//add to attach the article id
if ($data->article_id) {
$image->articles()->attach($data->article_id);
}
array_push($images, $image);
} else {
return response()->json(['invalid_file_format'], 422);
}
}
return $images;
}
and my folder structure looks like this:

Laravel - "Unable to write in the "/var/www/html/laraapp/public/storage/documents/appraisal_goal" directory"

I deployed my Laravel-5.8 application on Digital Ocean which uses Ubuntu-18. When I wanted to save image into my Laravel App on Digital Ocean:
public function create()
{
$userCompany = Auth::user()->company_id;
$userEmployee = Auth::user()->employee_id;
$identities = DB::table('appraisal_identity')->select('id','appraisal_name')->where('company_id', $userCompany)->where('is_current', 1)->first();
$employees = DB::table('hr_employees')->select('id')->where('id', $userEmployee)->first();
// dd($employees);
$goaltypes = AppraisalGoalType::where('company_id', $userCompany)->get();
$categories = AppraisalGoalType::with('children')->where('company_id', $userCompany)->whereNull('parent_id')->get();
return view('appraisal.appraisal_goals.create')
->with('goaltypes', $goaltypes)
->with('categories', $categories)
->with('identities', $identities)
->with('employees', $employees)
;
}
public function store(StoreAppraisalGoalRequest $request)
{
$appraisalStartDate = Carbon::parse($request->appraisal_start_date);
$appraisalEndDate = Carbon::parse($request->appraisal_end_date);
$userCompany = Auth::user()->company_id;
$employeeId = Auth::user()->employee_id;
$identities = DB::table('appraisal_identity')->select('id','appraisal_name')->where('company_id', $userCompany)->where('is_current', 1)->first();
$employees = DB::table('hr_employees')->select('id')->where('id', $employeeId)->first();
DB::beginTransaction();
try {
$goal = new AppraisalGoal();
$goal->goal_type_id = $request->goal_type_id;
$goal->appraisal_identity_id = $request->appraisal_identity_id;
$goal->employee_id = $request->employee_id; //$employeeId; //$request->employees_id
$goal->weighted_score = $request->weighted_score;
$goal->goal_title = $request->goal_title;
$goal->goal_description = $request->goal_description;
$goal->company_id = Auth::user()->company_id;
$goal->created_by = Auth::user()->id;
$goal->created_at = date("Y-m-d H:i:s");
$goal->is_active = 1;
if ($request->appraisal_doc != "") {
$appraisal_doc = $request->file('appraisal_doc');
$new_name = rand() . '.' . $appraisal_doc->getClientOriginalExtension();
$appraisal_doc->move(public_path('storage/documents/appraisal_goal'), $new_name);
$goal->appraisal_doc = $new_name;
}
$goal->save();
foreach ( $request->activity as $key => $activity){
$startDate = Carbon::parse($request->start_date[$key]);
$endDate = Carbon::parse($request->end_date[$key]);
$goaldetail = new AppraisalGoalDetail();
$goaldetail->kpi_description = $request->kpi_description[$key];
$goaldetail->appraisal_doc = $request->application_doc[$key];
$goaldetail->activity = $request->activity[$key];
$goaldetail->start_date = $startDate ->toDateTimeString();
$goaldetail->end_date = $endDate->toDateTimeString();
$goaldetail->appraisal_goal_id = $goal->id;
$goaldetail->appraisal_identity_id = $goal->appraisal_identity_id;
$goaldetail->employee_id = $goal->employee_id;
$goaldetail->company_id = Auth::user()->company_id;
$goaldetail->created_by = Auth::user()->id;
$goaldetail->created_at = date("Y-m-d H:i:s");
$goaldetail->is_active = 1;
$goaldetail->save();
}
$min_date = AppraisalGoalDetail::select('start_date')->where('appraisal_goal_id', $goal->id)->min('start_date');
$max_date = AppraisalGoalDetail::select('end_date')->where('appraisal_goal_id', $goal->id)->max('end_date');
$parentid = AppraisalGoalType::select('parent_id')->whereNotNull('parent_id')->where('company_id', $userCompany)->where('id', $goal->goal_type_id)->first();
$goal->update([
'appraisal_start_date' => $min_date,
'appraisal_end_date' => $max_date,
'parent_id' => $parentid->parent_id
]);
DB::commit();
Session::flash('success', 'Appraisal Goal is created successfully');
return redirect()->route('appraisal.appraisal_goals.index');
} catch (Exception $exception) {
dd($exception->getMessage());
DB::rollback();
Session::flash('error', 'Action failed! Please try again');
return redirect()->route('appraisal.appraisal_goals.index');
}
}
Everything works perfectly on the local server. But when I deployed it online to Digital Ocean. Then, when I click on submit, I got this error:
"Unable to write in the "/var/www/html/laraapp/public/storage/documents/appraisal_goal" directory"
How do I resolve it?
Thank you
You do not have necessary permission to write in storage folder.
Execute below command to provide necessary permission to write in storage folder
chmod 755 -R /var/www/html/laraapp/public/storage
chown www-data:www-data /var/www/html/laraapp/public/storage

Error Call to a member function getRealPath() on bool

I am get this error"Call to a member function getRealPath() on bool"
if($request->hasFile('content')) {
$filenameWithExt = $request->file('content')->getClientOriginalName();
$filename = pathinfo($filenameWithExt,PATHINFO_FILENAME);
$extension = $request->file('content')->getClientOriginalExtension();
$fileNameToStore = $filename.'_'.time().'.'.$extension;
$path = $request->file('content')->storeAs('public/content',$fileNameToStore);
} else {
$fileNameToStore = 'No Image,Music and Video selected please! check and try again.';
}
$post = new Post;
$post->body = $request->input('body');
$post->content = $fileNameToStore;
//Error exist here
$post = Image::make($fileNameToStore->getRealPath());
$post->text('The quick brown fox jumps over the lazy dog.');
$post->save();
getRealPath() is the method of SplFileInfo
See: https://www.php.net/manual/en/splfileinfo.getrealpath.php
If u want to use getRealPath(), try this:
Image::make(
$request->file('content')->getRealPath()
)->save('public/content',$fileNameToStore);

function str_slug is deprecated and not working, what should i do?

I was trying to use Str_slug but it is not working in laravel 5.8.
I am using PhpStorm latest version.
$product->slug = Str_slug('$request->title');
Check the image for more
public function ProductStore(StoreValidation $request){
$product = new product();
$product->category_id = 1;
$product->brand_id = 1;
$product->title = $request->title;
$product->desc = $request->desc;
$product->slug = Str_slug('$request->title');
$product->quantity = $request->quantity;
$product->price = $request->price;
$product->offer_price = $request->offer;
$product->status = 1;
$product->admin_id = 1;
// Saving Product information into product table
$product->save();
if ($request->hasFile('uploadFile')){
$image = $request->file('uploadFile');
$img = time() . '.' . $image->getClientOriginalExtension();
$location = public_path('image/product/' .$img);
$img_ins = Image::make($image)->resize(220,294);
$img_ins->save($location);
$product_img = new product_image();
$product_img->product_id = $product->id;
$product_img->image_name = $img;
$product_img->save();
}
return redirect()->route('admin_panel.pages.admin-addProduct');
}
You should use Str::slug() (Illuminate\Support\Str) instead of deprecated str_slug().
https://laravel.com/docs/5.8/helpers#method-str-slug

Problem uploading images with Axios and Laravel

I'm trying to upload and save images with Axios and a Laravel API, but i'm getting a 422 error.
I've tested with Postman and i have the same result, i have a similar controller**(without the Foreach)** but to upload only one image at once and it works fine.
///Axios
async submitFiles(){
let fd = new FormData()
for(var i = 0; i < this.files.length; i++){
let file = this.files[i]
fd.append('photo[' + i + ']', file)
}
try{
await this.$axios.$post(`/albums/${this.$route.params.id}/photos`, fd, {headers:{'Content-Type': 'multipart/form-data'}})
console.log(...fd)
alert('uploaded')
this.files = []
}
catch(err){
console.log(err)
alert(err)
}
}
//Laravel
class PhotosInAlbumController extends Controller
{
public function store(PhotoInAlbumRequest $request, Album $album)
{
if($request->hasfile('photo'))
{
$photo = new PhotoInAlbum();
$photo->photo = $request->photo;
$images[] = $request->file('photo');
foreach ($images as $image)
{
$filenameWithExt = $image->getClientOriginalName();
$filename = pathInfo($filenameWithExt, PATHINFO_FILENAME);
$extension = $image->getClientOriginalExtension();
$filenameToStore = $filename.'_'.time().'.'.$extension;
$path = $image->storeAs('photo/images', $filenameToStore,'public');
$photo->photo = $path;
$album->photos()->save($photo);
}
}
return $photo;
}
}
Hope someone can help me to figure out what's going on.
Thanks in advance (=
First, sorry I can't comment yet. But I see in this line:
$images[] = $request->file('photo');
that a bi-dimensional array is built. I would try the assignment without the brackets:
$images = $request->file('photo');

Resources