I want to Download multiple images as a zip file using laravel 7 - laravel

I am a beginner at laravel and I want to downloads multiple images as a zip file using laravel but I do not have an idea how can I do that please help me thanks.
InboxController
public function dowloads($id)
{
$clientfiles = Inbox::where('id', $id)->first();
dd($clientfiles->file);
// "["phpIgRq3Q.jpg","phpe6b34M.jpg","phpnPGN2M.png","php8CQh5P.jpg"]"
$files =config('yourstitchart.file_url');
// $files = "http://localhost/yourstitchart.com/web/public/uploads/images/"
}
HTML view
<a href="{{ route('download.inbox',$digitizingInbox->id) }}" class="download
btn btn-warning">Download
</a>
Route
Route::get('downloads/{id}/files','DigitizingInboxController#dowloads')->name('download.inbox');

You can also use Chumper/Zipper package to make zip files. It is used by many developers. check here
You can try it like:
$zipper = Zipper::make(public_path('/documents/deals.zip'));
$clientfiles = Inbox::where('id', $id)->first();
foreach ($clientfiles->file as $file) {
$zipper->add(public_path($file)); // update it by your path
}
$zipper->close();
return response()
->download(
public_path('/temporary_files/' . "deals.zip"),
"deals.zip",
["Content-Type" => "application/zip"]
);

Related

Getting 404 on images in public folder using a custom function in Laravel

I'm trying to use a simple function to auto-populate the images in a gallery page, but getting 404's on the images. Everything else is working as intended.
I'm using material css and all of that fluff is working correctly. I'm getting the correct number of image cards.
The path echoed out correctly, and within the function the name of the images is being generated with no issues. I'm using the {{asset}} function of Laravel and my images are in the public folder, so access shouldn't (?) be an issue.
public static function addImg($dirname){
$images = scandir($dirname);
$ignore = Array(".", "..");
foreach($images as $curimg){
if(!in_array($curimg, $ignore)) {
echo "<div class='col s12 m6 l4'>
<img src='{{asset({$dirname}{$curimg})}}' class='materialbox responsive-img card'>$curimg
</div>";
}
}
}
and the call is
{{$gallery::addImg('/css/img/')}}
Console shows "GET http://127.0.0.1:8000/%7B%7Basset(~snip for privacy~/public/css/img/hero%20(2).jpg)%7D%7D 404 (Not Found)"
You are using Blade syntax in a regular string. It isn't going to be parsed. You have to return the string how you actually need it to be.
Any interpolation you need has to be done while defining the string like any other regular string in PHP.
$location = asset($dirname . $curimage);
echo "<img src='{$location}' ...>{$curimage}";
Also you are calling {{ $gallery::addImg(...) }} which doesn't return anything that could be echoed by Blade. {{ }} is for echoing in Blade, it is not for just executing PHP statements.
This sounds like something you could make into a custom Blade directive though.
You can't use blade syntax inside a string because blade will parse only the .blade.php file.
But you can just use simple php concatenation:
public static function addImg($dirname){
$images = scandir($dirname);
$ignore = Array(".", "..");
foreach($images as $curimg){
if (!in_array($curimg, $ignore)) {
echo "<div class='col s12 m6 l4'>
<img src='" . asset($dirname . $curimg) . "' class='materialbox responsive-img card'>$curimg
</div>";
}
}
}

laravel blade include files with relative path

In laravel blade system when we want to include a partial blade file we have to write the full path every time for each file. and when we rename a folder then we will have to check every #include of files inside it. sometimes it would be really easy to include with relative paths. is there any way to do that?
for example we have a blade file in this path :
resources/views/desktop/modules/home/home.blade.php
and I need to include a blade file that is near that file :
#include('desktop.modules.home.slide')
with relative path it would be something like this :
#include('.slide')
is there any way to do this?
if someone still interest with relative path to current view file, put this code in the boot method of AppServiceProvider.php or any provider you wish
Blade::directive('relativeInclude', function ($args) {
$args = Blade::stripParentheses($args);
$viewBasePath = Blade::getPath();
foreach ($this->app['config']['view.paths'] as $path) {
if (substr($viewBasePath,0,strlen($path)) === $path) {
$viewBasePath = substr($viewBasePath,strlen($path));
break;
}
}
$viewBasePath = dirname(trim($viewBasePath,'\/'));
$args = substr_replace($args, $viewBasePath.'.', 1, 0);
return "<?php echo \$__env->make({$args}, \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>";
});
and then use
#relativeInclude('partials.content', $data)
to include the content.blade.php from the sibling directory called partials
good luck for everyone
you need to create custom blade directive for that, the native include directive doesn't work like that.
read this page to learn how to create custom blade directive :
https://scotch.io/tutorials/all-about-writing-custom-blade-directives
\Blade::directive('include2', function ($path_relative) {
$view_file_root = ''; // you need to find this path with help of php functions, try some of them.
$full_path = $view_file_root . path_relative;
return view::make($full_path)->render();
});
then in blade file you can use relative path to include view files :
#include2('.slide')
I tried to tell you the idea. try and test yourself.
There’s now a package doing both relative and absolute includes (lfukumori/laravel-blade-include-relative) working with #include, #includeIf, #includeWhen, #each and #includeFirst directives. I just pulled it in a project, it works well.
A sleek option, in case you want to organise view files in sub-folders:
public function ...(Request $request) {
$blade_path = "folder.subfolder.subsubfolder.";
$data = (object)array(
".." => "..",
".." => $..,
"blade_path" => $blade_path,
);
return view($data->blade_path . 'view_file_name', compact('data'));
}
Then in the view blade (or wherever else you want to include):
#include($blade_path . 'another_view_file_name')

Tracking clicks on Download button and save in database

I have simple Download button which is looks like this
<a download="{{ $thumb }}" href="{{ $thumb }}" class="btn btn-success">Download Image</a>
It is appearing on page when the image is found. The button is working perfectly and is downloading the image.
The page has simple input field which user can search the image and if image is found it's showed on page with button download.
I've made a function which saves each string which is searched and now I'm wondering if I can save also if button Download is clicked e.g. the image is downloaded.
Can someone show me an example? I'm using laravel 5.4 here. So maybe I need to pass to the controller click event?
Current controller function
public function getImage(Request $request)
{
$url = get_curl_content_tx('http://example.com/api?url='.$request->input('url'));
$items = json_decode($url, true);
$thumb = $items['thumbnail_url'];
$db_save = new Image();
$ip = $request->ip();
$ip = DB::connection()->getPdo()->quote($ip);
$db_save->url = $request->input('url');
$db_save->ip = DB::raw("inet_aton($ip)");
$db_save->save();
return view('getImage',compact('thumb'));
}
Yes. Make sure that the href is going to a route where you keep track of these records and you can pass on the specific image to update the Record Model of the Image model itself if the counter is there? Something like this:
public function TrackDownload(Image $image){
$imageRecord = Record::where('image_id', '=', $image->id);
$imageRecord->update([
'download_counter' => $imageRecord->download_counter + 1;
]);
return redirect()->route();
}

Laravel display image from path which is in database

So use is uploading a logo and it's path is stored in a database like this:
C:\xampp\htdocs\laravel\public\logo\1496912432.jpg
I am displaying the image like this:
<img class="images" id="image" src="{{$business->image}}" />
However I get this error:
Not allowed to load local resource: file:///C:/xampp/htdocs/laravel/public/logo/1496912432.jpg
How can this problem be solved?
//edit
Controller:
public function image(Request $request) {
if($request->hasFile('img'))
{
$image = Input::file('img');
$filename = time() . '.' . $image->getClientOriginalExtension();
$path = public_path('logo/' . $filename);
Image::make($image->getRealPath())->fit(303, 200)->save($path);
$file = $request->file('img');
$session = session()->get('key');
$update_image = Business::find($session);
$update_image->image = $path;
$update_image->save();
return ['url' => url('logo/' . $filename)];
}
Use Laravel file() to store files https://laravel.com/docs/5.4/requests#files
Store the $path to your db
$path = $request->photo->store('logo');
the $request->photo is depending on your input file attribute name. In your case, it should be $request->img.
the above code will create a folder (if not exist), namely "logo" and store to that folder with random string file name.
Also check your configuration for file, located at /config/filesystem.php. Default is set to public
Use asset function to get the full path from public folder
<img class="images" id="image" src="{{ asset($business->image }}" />
You can do in two ways
Best way is update url path when image saving save url path to db
$path = $request->photo->store('logo'); // in 5.4
The other way if you can't changes db url you can do some hack like this
$file = explode('/public/', $business->image);
echo asset($file[1]);
You want to store all files inside the web root. Because of cross-domain security, you cannot access the file:// domain/protocol from a http protcol. By using Laravel to store and retrieve, it will come from the same host.

Access images inside public folder in laravel

How can I access the images stored inside public/images folder without the use of Laravel's own functions like assets()?
I just want to get the direct URL of the images stored in images folder.
Eg:
localhost/webapp/images/stackoverflow.png
When requesting the link i should get the direct image.
If you are inside a blade template
{{ URL::to('/') }}/images/stackoverflow.png
Just put your Images in Public Directory (public/...folder or direct images).
Public directory is by default rendered by laravel application.
Let's suppose I stored images in public/images/myimage.jpg.
Then in your HTML view, page like: (image.blade.php)
<img src="{{url('/images/myimage.jpg')}}" alt="Image"/>
I have created an Asset helper of my own.
First I defined the asset types and path in app/config/assets.php:
return array(
/*
|--------------------------------------------------------------------------
| Assets paths
|--------------------------------------------------------------------------
|
| Location of all application assets, relative to the public folder,
| may be used together with absolute paths or with URLs.
|
*/
'images' => '/storage/images',
'css' => '/assets/css',
'img' => '/assets/img',
'js' => '/assets/js'
);
Then the actual Asset class:
class Asset
{
private static function getUrl($type, $file)
{
return URL::to(Config::get('assets.' . $type) . '/' . $file);
}
public static function css($file)
{
return self::getUrl('css', $file);
}
public static function img($file)
{
return self::getUrl('img', $file);
}
public static function js($file)
{
return self::getUrl('js', $file);
}
}
So in my view I can do this to show an image:
{{ HTML::image(Asset::img('logo.png'), "My logo")) }}
Or like this to implement a Java script:
{{ HTML::script(Asset::js('my_script.js')) }}
when you want to access images which are in public/images folder and if you want to access it without using laravel functions,
use as follows:
<img src={{url('/images/photo.type')}} width="" height="" alt=""/>
This works fine.
You simply need to use the asset helper function in Laravel. (The url helper can also be used in this manner)
<img src="{{ asset('images/arrow.gif') }}" />
For the absolute path, you use public_path instead.
<p>Absolute path: {{ public_path('images/arrow.gif') }}</p>
If you are providing the URL to a public image from a controller (backend) you can use asset as well, or secure_asset if you want HTTPS. eg:
$url = asset('images/arrow.gif'); # http://example.com/assets/images/arrow.gif
$secure_url = secure_asset('images/arrow.gif'); # https://example.com/assets/images/arrow.gif
return $secure_url;
Lastly, if you want to go directly to the image on a given route you can redirect to it:
return \Redirect::to($secure_url);
More Laravel helper functions can be found here
In my case it worked perfectly
<img style="border-radius: 50%;height: 50px;width: 80px;" src="<?php echo asset("storage/TeacherImages/{$teacher->profilePic}")?>">
this is used to display image from folder i hope this will help someone looking for this type of code
Crete file .htaccess in root && add
...
RewriteCond %{REQUEST_URI} !(.css|.js|.png|.jpg|.gif|robots.txt|.ttf)$ [NC]
...

Resources