LARAVEL - MULTIPLE FILE UPLOAD DOESNT WORK AND RETRIEVING - laravel

When I click on submit, it's only storing last selected file where it suppose to store all the images and how to retrieve those files? Any suggestion or example? Do I need to have different attributes for multiple files?
Controller
if (is_array($request->carEvidence)) {
foreach ($request->carEvidence as $key => $file) {
$destinationPath = public_path('image/');
$profileImage = $key . "-" . date('YmdHis') . "." . $file->getClientOriginalExtension();
$file->move($destinationPath, $profileImage);
$post['carEvidence'] = "$profileImage";
}
}
Views
<input type="file" name="carEvidence[]" multiple>
MYSQL
https://ibb.co/9sPLw8C
File Input
https://ibb.co/VHkxRwc

you are passing multiple files in array, so you have to use loop to retrieve all the files in controller.. something like
if (is_array($request->carEvidence))
{
foreach ($request->carEvidence as $key => $file) {
$destinationPath = public_path('image/');
$profileImage = $key."-".date('YmdHis') . "." . $file->getClientOriginalExtension();
$file->move($destinationPath, $profileImage);
// code to save in your db table
}
}

Related

Image does not displayed - How to display an image perhaps dynamically

I would like to display an employee picture using the url as shown below which I think should work but not. However it does work with the second url which is static. why is this happening?
This the first url that does not work
<img id="message" src="{{url('/profile_picture/' . $employee->picture)}}" style="width: 150px;"/>
This is the second url that does work
<img id="message" src="{{url('/profile_picture/20220615232745.jpg')}}" style="width: 150px;"/>
To save a picture I use the following method
public function ProfileStore(Request $request)
{
$data = User::find(Auth::user()->id);
$data->name =$request->name;
$data->email =$request->email;
if ($request->file('picture')) {
$file = $request->file('picture');
$filename = date('YmdHis') . "." . $file->getClientOriginalExtension();
$file->move('profile_picture/', $filename);
$data['picture'] = " $filename";
}
$data->save();
return redirect()->route('profile.index');
}
The route
Route::post('/people/employees/profiles/store', [ProfileController::class, 'ProfileStore'])->name('profile.store');
Route::get('/people/employees/profiles/edit/{id}', [ProfileController::class, 'ProfileEdit'])->name('profile.edit');
My edit method
public function ProfileEdit()
{
$id = Auth::user()->id;
$employee = User::find($id);
return view('fms.people.employee.profiles.profile_edit')->with('employee',$employee);
}
in you profilestore function, when setting the $filename to $data['picture'], you have extra space before it.Remove that space and try again. For ex:
if ($request->file('picture')) {
$file = $request->file('picture');
$filename = date('YmdHis') . "." . $file->getClientOriginalExtension();
$file->move('profile_picture/', $filename);
$data['picture'] = "$filename";
}

Laravel deploy: storage image doesn't work correctly

After deploying my laravel project from local to Apache web server, all works correctly except images link. Here the code:
Images are stored in:
storage/app/public/photos
after i've run command:
php artisan storage:link
Images are linked at:
public/storage/photos
Controller:
if ($request->hasFile('photo')) {
$extension = $request->file('photo')->getClientOriginalExtension();
$file = $request->file('photo');
$photo = $file->storeAs('public/photos', 'foto-' . time() . '.' . $extension);
$user->photo = $photo;
$user->save();
}
Images are uploaded correctly on storage/app/public/photos and correctly linked in public/storage/photos but it doesn't display on frontend.
in blade, i've tried to use Storage::url to retrieve the path
{{Storage::url($user->photo)}}
and asset()
{{asset($user->photo)}}
in both cases, image doesn't exist
The public path of image is:
http://mywebsite.com/storage/photos/foto-1522914164.png
You should Use url function to show your image like below way.
url($user->photo);
I'd suggest to change the controller code as follows:
if ($request->hasFile('photo')) {
$extension = $request->file('photo')->getClientOriginalExtension();
$file = $request->file('photo');
$photoFileName = 'foto-' . time() . '.' . $extension;
$photo = $file->storeAs('public/photos', $photoFileName);
$user->photo = 'photos/' . $photoFileName;
$user->save();
}
Then you can use {{asset($user->photo)}} in your blade.
on my webspace, it seems that the only way to display image correctly is to create a custom route that read and serve the image.
i'm solved like this:
i'm storing only image name in db:
if ($request->hasFile('photo')) {
$extension = $request->file('photo')->getClientOriginalExtension();
$file = $request->file('photo');
$photoFileName = 'photo-' . $model->id . '.-' . time() . '.' . $extension;
$photo = $file->storeAs('public/photos', $photoFileName);
$store = $photoFileName;
}
then, i've create custom route that read images and display them:
Route::get('storage/{filename}.{ext}', function ($filename, $ext) {
$folders = glob(storage_path('app/public/*'), GLOB_ONLYDIR);
$path = '';
foreach ($folders as $folder) {
$path = $folder . '/' . $filename . '.' . $ext;
if (File::exists($path)) {
break;
}
}
if (!File::exists($path)) {
abort(404);
}
$file = File::get($path);
$type = File::mimeType($path);
$response = Response::make($file, 200);
$response->header('Content-Type', $type);
return $response;
});
in blade, i'm using Storage to display image:
{{ Storage::url($photo->photo) }}}

Uploading multiple files in Laravel 5

I have been trying to upload multiple files in Laravel using the code below but it only uploads a single image. Please help
$files = $request->file('file');
foreach ($files as $file){
$filename = time().'.'.$file->getClientOriginalExtension();
$location = public_path('uploads/'.$filename);
$file->move(public_path().'/uploads/', $filename);
$filename_arr = [];
array_push($filename_arr, $filename);
$filename = json_encode($filename_arr);
$upload->filename = $filename;
}
Blade: As you want to upload multiple file append [] to the input type name property with multiple as below :
<input type="file" name="file[]" multiple>
Logic:
if($request->hasFile('file'))
{
$files = $request->file('file');
foreach ($files as $file) {
$filename = $file->getClientOriginalName();
$file->move(public_path().'/uploads, $filename);
}
}

Laravel 5.4 Error: NotReadableException: Image source not readable

I'm trying to create multiple copies of profile pic in different sizes when a profile is created. But I am constantly getting this error:
" NotReadableException: Image source not readable"
Can somebody point me what I'm missing in my below code:
public function updateprofile(UserProfileRequest $request){
$user_id = Auth::User()->id;
$profile = UserProfile::where('user_id','=',$user_id)->first();
$profile->fullname = $request->fullname;
if ($request->hasFile('img')) {
if($request->file('img')->isValid()) {
$types = array('_original.', '_32.', '_64.', '_128.');
$sizes = array( '32', '64', '128');
$targetPath = 'public/uploads/'.$user_id;
try {
$file = $request->file('img');
$ext = $file->getClientOriginalExtension();
$fName = time();
$original = $fName . array_shift($types) . $ext;
Storage::putFileAs($targetPath, $file, $original);
foreach ($types as $key => $type) {
$newName = $fName . $type . $ext;
Storage::copy($targetPath . $original, $targetPath . $newName);
$newImg = Image::make($targetPath . $newName);
$newImg->resize($sizes[$key], null, function($constraint){
$constraint->aspectRatio();
});
$newImg->save($targetPath . $newName);
}
$profile->img = 'public/uploads/'.$user_id;
} catch (Illuminate\Filesystem\FileNotFoundException $e) {
}
}
}
$profile->save();}
I had the same issue i ran this command and it worked
php artisan storage:link
This command creates a storage directory under the public folder.
Also use public path function to get the public path
$targetPath = public_path('storage/uploads/'. $user_id);
The 'storage' used inside the laravel public_path() function is used to get the storage main folder.
If I'm not mistaken, the path which is provided should be the absolute filepath on your server. For example instead of:
$targetPath = 'public/uploads/'.$user_id;
Use (your actual path will vary depending on your configuration)
$targetPath = '/var/www/sitename/public/uploads/'.$user_id;
Laravel also contains a helper function called public_path() which can be used to obtain the "fully qualified path to the public directory". This would allow you to use something such as:
$targetPath = public_path('uploads/'. $user_id);
Also, on this line, do not forget to place a slash before the new filename:
$newImg = Image::make($targetPath . '/' . $newName);
I would also confirm that the user executing the script (if apache or nginx usually www-data unless altered) has write permissions to your public/uploads/ directory
Finally, I got it working. I made following changes to my code:
Use the full OS path as suggested by commanderZiltoid for the destination path.
Don't use Storage::putFileAs method to save the file. So, remove this line: Storage::putFileAs($targetPath, $file, $original);
Don't use Storage::copy() to copy the file, so, remove this line:
Storage::copy($targetPath . $original, $targetPath . $newName);
For points 2 and 3, use Image::make($file->getRealPath()); This will create the file and remember the path where the file was created. Image->resize method will use this path later.
In the end, save the relative path in the database, as here: $profile->img = 'storage/uploads/'.$user_id.'/img/profile/'.$fName. Since we'll use {{ asset($profile->img) }}, it's necessary to save only the relative path and not the absolute OS path.
if($request->hasFile('img')) {
if($request->file('img')->isValid()) {
$types = array('_original.', '_32.', '_64.', '_128.');
$sizes = array( array('32','32'), array('64','64'), array('128','128'));
$targetPath = '/Users/apple/Documents/_chayyo/chayyo/storage/app/public/uploads/'.$user_id.'/img/profile/';
try {
$file = $request->file('img');
$ext = $file->getClientOriginalExtension();
$fName = time();
$o_name = $fName . array_shift($types) . $ext;
$original = Image::make($file->getRealPath());
$original->save($targetPath . $o_name);
foreach ($types as $key => $type) {
$newName = $fName . $type . $ext;
$newImg = Image::make($file->getRealPath());
$newImg->resize($sizes[$key][0], $sizes[$key][1]);
$newImg->save($targetPath . $newName);
}
$profile->img = 'storage/uploads/'.$user_id.'/img/profile/'.$fName;
}
catch (Illuminate\Filesystem\FileNotFoundException $e) {
}
}
}

i m saving the multiple images at a single time with differnt ID in database in Laravel

and it is saved but the issue is all the images have different auto
increment ids in database i want to save the images with the same ids
which is save at the same time,kindly guide me.
****strong text** the code is below;**
$field = Input::file('image');
$location = public_path('uploads/');
foreach ($field as $k => $fd) {
$filename = str_random(2).'-' . time() . "." . $fd->getClientOriginalExtension();
$fd->move($location , $filename);
$product->image = $filename;
}
$user->save();
I think bellow code helps you..
You can try.
$picture = '';
if ($request->hasFile('image')) {
$files = $request->file('image');
foreach($files as $file){
$filename = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$picture = date('His').$filename;
$destinationPath = base_path() . '\public\images';
$file->move($destinationPath, $picture);
}
}
if (!empty($product['images'])) {
$product['images'] = $picture;
} else {
unset($product['images']);
}

Resources