is there any possibility to display image from public folder in Laravel controller? - laravel

this function returns only one image. but I want to show all images which are stored in this folder. can anyone help me?
My controller
public function index()
{
$get=Resturant::all(['id','name','image']);
foreach ($get as $image) {
$path =public_path().'/Images/Resturants/'.$image->image;
$file= File::get($path);
$type= File::mimeType($path);
$response= Response::make($file, 200);
$response->header("Content-Type",$type);
return $response;
}
}

You don't need to be trying to return a file response, since your web server itself can handle serving files in the public folder. Also you wouldn't be trying to return multiple files (somehow) in the response. You can just return an array of the URLs to the files and let what ever is consuming this make the requests to get these files by URL. This would simplify your controller method quite a bit:
return Resturant::pluck('image')
->map(fn ($i) => asset('Images/Resturants/'. $i));
PHP 8 here, but its pretty simple, just have to make URLs from each image.
If you want to have the names to go along with this you can adjust pluck to use a column for the index:
...pluck('image', 'name')...

Related

Return multiple PDF views using one route

I would like to know if it's possible to display multiple PDF files using one route (with package Barryvdh\DomPDF). Would be something like this :
User clicks on link "Download all files";
Link points towards method downloadAll()
This method returns multiple streams with foreach using either queues, workers or anything else that could help (each time _blank page).
My current method :
public function downloadAll(Person $person)
{
foreach ($person->letter as $letter) {
dispatch(function () use ($letter) {
return Pdf::loadView('cancellation-letter', [
'letter' => $letter,
])->stream($letter->uuid . '.pdf');
});
}
return redirect()->back();
}
Obviously this won't work, since method cannot return multiple responses. But is this possible to do in the first place? And if yes, would you have any advice on how i could do this?

Replace Old image with new image in laravel

CONTROLLER
public function updateproduct(Request $request, $id)
{
// dd($request->all());
$request->validate([
'name'=>'required',
'description'=>'required',
'price'=>'required|numeric',
'quantity'=>'required|numeric',
]);
$product = Product::where('id', $id)->first();
if(is_null($product)) {
$product = new Product();
}
$product->name=$request->name;
$product->description=$request->description;
$product->price=$request->price;
$product->quantity=$request->quantity;
if($request->hasfile('images')){
$existingimages = Image::where(['product_id'=> $product->id, 'source'=> 1])->get();
if($existingimages->count() > 0)
foreach($existingimages as $existingimage) {
$filename = public_path().'files/'.$existingimage->name;
if(file_exists($filename)){
unlink($filename);
$existingimage->delete();
}
}
foreach($request->file('images') as $file){
$name = rand(1,9999).'.'.$file->getClientOriginalName().$file->getClientOriginalExtension();
if($file->move(public_path().'/files/', $name)){
$updateImage = Image::firstWhere('product_id', $product->id);
$updateImage->images = $name;
$updateImage->source = 1;
$updateImage->save();
}
}
}
Please check updated question. Request you to correct me if I wrong. Right now it only updates 1 image and other images remains same. please help me with this.
Your code is somewhat confusing, I'm afraid.
Your request appears to allow for multiple images to be uploaded. Here :
if(file_exists($imagePath)){
unlink($imagePath);
}
you look like you're trying to delete any images that already exist, but when you store upload images you're assigning them a random name (which Laravel can already handle for you, by the way, so there's no need to do it yourself) so you're unlikely to be actually deleting them because there'll likely be no file at that location anyway.
Nowhere does your code actually delete any existing images from the database. Essentially what you want to do is :
If the upload has images, retrieve all the existing images for that product.
Delete the physical files for those existing images.
Delete the database entries for those existing images.
Upload your new images and save their details to the database.
Translating that into code means :
if($request->hasfile('images')){
// Delete any existing image files and database entries.
$existingimages = Image::where('product_id', $product->id)->get();
if($existingimages->count() > 0)
foreach($existingimages as $existingimage) {
$filename = public_path().'files/'.$existingimage->name;
unlink($filename);
$existingimage->delete();
}
}
// Carry on with your upload
}
It adds new images because you are using the Image::create method. If I understood correctly, you want to modify the images of your products in the image table.
Try to modify your code like :
$updateImage = Image::firstWhere('product_id', $product->id);
$updateImage->images = $name;
$updateImage->source = 1;
$updateImage->save();

barryvdh/laravel-dompdf renders blank web page

I'm upgrading from Laravel 7 to 8 and would like to switch to barryvdh/laravel-dompdf for PDF generation. I was using niklasravnsborg/laravel-pdf up until now, but since that package doesn't support Laravel 8, I need to switch. So I am in the processing of altering my existing code to use barryvdh/laravel-dompdf, but I'm running into an issue.
This is my (simplified) controller:
public function update(Request $request) {
$invoice = Invoice::find($request->invoice_id);
if(isset($request->export) AND $request->export == 1) {
$this->exportInvoice($invoice, $request);
}
}
This exportInvoice function is in the same controller file.
I'm using this to generate a test PDF:
$pdf = App::make('dompdf.wrapper');
$pdf->loadHTML('<h1>Test</h1>');
return $pdf->stream();
Now I've managed to narrow down the issue to the place in my code where the PDF generation fails.
If I put the PDF generation code in the if statement in the update function above, then I get the expected result: a simple PDF file.
However, as soon as I move this piece of code to the exportInvoice function, I get a simple blank web page.
I've been googling around, but I was unable to find similar issues.
I've tried putting all my code together in the update function and guess what ... This works as expected. It's as if I'm doing something wrong with the subfunctions, but I can't figure out what.
Does anybody see what I'm doing wrong?
From your update() method, this will stream a PDF back to the browser:
return $pdf->stream();
But from a exportInvoice(), called by the update() method, that will just return the stream back to the update() method. If you don't do anything with it there, it won't reach the browser. You need to return the response returned from exportInvoice().
public function update(Request $request) {
$invoice = Invoice::find($request->invoice_id);
if(isset($request->export) AND $request->export == 1) {
// Note we need to *return* the response to the browser
return $this->exportInvoice($invoice, $request);
}
}
public function exportInvoice($invoice, $request) {
$pdf = App::make('dompdf.wrapper');
$pdf->loadHTML('<h1>Test</h1>');
return $pdf->stream();
}

Error showing when Delete image in laravel

I want to delete images that I store in server,
I store images like this
$image1 = $postData['img']['0']->store('public');
$Add->Img1 = str_replace('public/', '', $image1 );
images save in public/storage folder
I display images like this
<img src="{{ asset('/storage/'.$add->Img1)}}">
so I need to delete this image using a tag like this
Remove
this is my route
Route::get('/deleteImg/{id}', 'AlladdsController#DeleteImg')->name('deleteImg');
this is my controller for delete images
public function DeleteImg (Request $request, alladds $alladds)
{
$img= request('id');
if(Storage::delete('/public'.'/'.$img)) {
return 'file is deleted';
}
else {
return 'file is not deleted';
}
return redirect()->back();
}
but this code is not working, what I want to do correct this code
Your route is injecting the id into the method DeleteImg(), but you have a different field catching the injected id.
This routing:
Route::get('/deleteImg/{id}', 'AlladdsController#DeleteImg')->name('deleteImg');
pushes id into the method as the argument after $request.
I don't know what alladds is, and it doesn't seem to be used, so I suggest following Laravel convention and re-write the method input like so:
// Note lower case to match route method and std.
public function deleteImg (Request $request, $img){ ... }
This will inject whatever you are sending into the route right into the method. This will fix the mismatch error (if that was even an error -- not sure as you didn't say what the exact issue was).
Also - note you are calling the asset from storage directory and then trying to delete the image from public- these are two different places, and may well be the cause of the error - perhaps one of these locations is incorrect and thus you are trying to delete (or call) from an area where it doesn't exist.

How to protect image from public view in Laravel 5?

I have installed Laravel 5.0 and have made Authentication. Everything is working just fine.
My web site is only open for Authenticated members. The content inside is protected to Authenticated members only, but the images inside the site is not protected for public view.
Any one writes the image URL directly can see the image, even if the person is not logged in to the system.
http://www.somedomainname.net/images/users/userImage.jpg
My Question: is it possible to protect images (the above URL example) from public view, in other Word if a URL of the image send to any person, the individual must be member and login to be able to see the image.
Is that possible and how?
It is possible to protect images from public view in Laravel 5.x folder.
Create images folder under storage folder (I have chosen storage folder because it has write permission already that I can use when I upload images to it) in Laravel like storage/app/images.
Move the images you want to protect from public folder to the new created images folder. You could also chose other location to create images folder but not inside the public folder, but with in Laravel folder structure but still a logical location example not inside controller folder. Next you need to create a route and image controller.
Create Route
Route::get('images/users/{user_id}/{slug}', [
'as' => 'images.show',
'uses' => 'ImagesController#show',
'middleware' => 'auth',
]);
The route will forward all image request access to Authentication page if person is not logged in.
Create ImagesController
class ImagesController extends Controller {
public function show($user_id, $slug)
{
$storagePath = storage_path('app/images/users/' . $user_id . '/' . $slug);
return Image::make($storagePath)->response();
}
}
EDIT (NOTE)
For those who use Laravel 5.2 and newer. Laravel introduces new and better way to serve files that has less overhead (This way does not regenerate the file as mentioned in the answer):
File Responses
The file method can be used to display a file, such as an image or
PDF, directly in the user's browser instead of initiating a download.
This method accepts the path to the file as its first argument and an
array of headers as its second argument:
return response()->file($pathToFile);
return response()->file($pathToFile, $headers);
You can modify your storage path and file/folder structure as you wish to fit your requirement, this is just to demonstrate how I did it and how it works.
You can also added condition to show the images only for specific members in the controller.
It is also possible to hash the file name with file name, time stamp and other variables in addition.
Addition: some asked if this method can be used as alternative to public folder upload, YES it is possible but it is not recommended practice as explained in this answer. So the same method can be also used to upload images in storage path even if you do not intend to protect them, just follow the same process but remove 'middleware' => 'auth',. That way you won't give 777 permission in your public folder and still have a safe uploading environment. The same mentioned answer also explain how to use this method with out authentication in case some one would use it or giving alternative solution as well.
In a previous project I protected the uploads by doing the following:
Created Storage Disk:
config/filesystems.php
'myDisk' => [
'driver' => 'local',
'root' => storage_path('app/uploads'),
'url' => env('APP_URL') . '/storage',
'visibility' => 'private',
],
This will upload the files to \storage\app\uploads\ which is not available to public viewing.
To save files on your controller:
Storage::disk('myDisk')->put('/ANY FOLDER NAME/' . $file, $data);
In order for users to view the files and to protect the uploads from unauthorized access. First check if the file exist on the disk:
public function returnFile($file)
{
//This method will look for the file and get it from drive
$path = storage_path('app/uploads/ANY FOLDER NAME/' . $file);
try {
$file = File::get($path);
$type = File::mimeType($path);
$response = Response::make($file, 200);
$response->header("Content-Type", $type);
return $response;
} catch (FileNotFoundException $exception) {
abort(404);
}
}
Serve the file if the user have the right access:
public function licenceFileShow($file)
{
/**
*Make sure the #param $file has a dot
* Then check if the user has Admin Role. If true serve else
*/
if (strpos($file, '.') !== false) {
if (Auth::user()->hasAnyRole(['Admin'])) {
/** Serve the file for the Admin*/
return $this->returnFile($file);
} else {
/**Logic to check if the request is from file owner**/
return $this->returnFile($file);
}
} else {
//Invalid file name given
return redirect()->route('home');
}
}
Finally on Web.php routes:
Route::get('uploads/user-files/{filename}', 'MiscController#licenceFileShow');
I haven't actually tried this but I found Nginx auth_request module that allows you to check the authentication from Laravel, but still send the file using Nginx.
It sends an internal request to given url and checks the http code for success (2xx) or failure (4xx) and on success, lets the user download the file.
Edit: Another option is something I've tried and it seemed to work fine. You can use X-Accel-Redirect -header to serve the file from Nginx. The request goes through PHP, but instead of sending the whole file through, it just sends the file location to Nginx which then serves it to the client.
if I am understanding you it's like !
Route::post('/download/{id}', function(Request $request , $id){
{
if(\Auth::user()->id == $id) {
return \Storage::download($request->f);
}
else {
\Session::flash('error' , 'Access deny');
return back();
}
}
})->name('download')->middleware('auth:owner,admin,web');
Every file inside the public folder is accessible in the browser. Anyone easily gets that file if they find out the file name and storage path.
So better option is to store the file outside the public folder eg: /storage/app/private
Now do following steps:
create a route (eg: private/{file_name})
Route::get('/private/{file_name}', [App\Http\Controllers\FileController::class, 'view'])->middleware(['auth'])->name('view.file');
create a function in a controller that returns a file path. to create a controller run the command php artisan make:controller FileController
and paste the view function in FileController
public function view($file)
{
$filePath = "notes/{$file}";
if(Storage::exists($filePath)){
return Storage::response($filePath);
}
abort(404);
}
then, paste use Illuminate\Support\Facades\Storage; in FileController for Storage
And don't forget to assign middleware (in route or controller) as your requirement(eg: auth)
And now, only those who have access to that middleware can access that file through a route name called view.file

Resources