Reputation: 152
I am new to Laravel and I trying to capture the filename stored on the database table called "Infrastructure" so that I can create a link for users to downloading that file. The download works but I always get the wrong file stored in the directory.
So in my controller called infrastructureController.php I have these codes.
public function show($id)
{
$infrastructure = $this->infrastructureRepository->find($id);
$Attachment = $infrastructure->inf_file; // captured filename in the database
if (empty($infrastructure)) {
Flash::error('Infrastructure not found');
return redirect(route('infrastructures.index'));
}
return view('infrastructures.show')->with('infrastructure', $infrastructure);
}
In my route or web.php
I have these codes...
Route::get('/download', function(){
$name = $Attachment;
$file = storage_path()."/app/public/infrastructure/".$Attachment;
$headers = array(
'Content-Type: application/pdf',
);
return Response::download($file, $name, $headers);
});
and finally, in my view file, I have this
<!-- Inf File Field -->
<div class="form-group">
{!! Form::label('inf_file', 'Attachements:') !!}
<a href="/download">Download Now</a>
</div>
Can someone point out I did wrong here...
Upvotes: 2
Views: 8698
Reputation: 2401
First you are not passing the name of the attachment from your View back to your controller so change your view to:
<!-- Inf File Field -->
<div class="form-group">
{!! Form::label('inf_file', 'Attachements:') !!}
<a href="/download/{{ $infrastructure->inf_file }}">Download Now</a>
</div>
Then in your route you need to access the name of the file like so:
Route::get('/download/{Attachment}', function($Attachment){
$name = $Attachment;
$file = Storage::disk('public')->get("infrastructure/".$Attachment);
$headers = array(
'Content-Type: application/pdf',
);
return Response::download($file, $name, $headers);
});
Upvotes: 3