Download file in laravel - laravel

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:') !!}
Download Now
</div>
Can someone point out I did wrong here...

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:') !!}
Download Now
</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);
});

Related

I am getting this error while want to update in the database

Missing required parameter for [Route: blog.update] [URI: blog/{post}/update] [Missing parameter: post].
in routes :
Route::put('/blog/{post}/update', [BlogController::class, 'update'])->name('blog.update');
in BlogController :
`
public function update(Request $request,Post $post){
$request->validate([
'title' => 'required',
'image' => 'required | image',
'body' => 'required'
]);
$postId = $post->id;
$title = $request->input('title');
$slug = Str::slug($title,'-').'-'.$postId;
// $user_id = Auth::user()->id;
$body = $request->input('body');
//File upload
$imagePath = 'storage/'. $request->file('image')->store('postImages','public');
// $post = new Post();
$post->title = $title;
$post->slug = $slug;
// $post->user_id = $user_id;
$post->body = $body;
$post->imagePath = $imagePath;
$post->save();
return redirect()->back()->with('status', 'Post edited successfully');
dd('validation passed . You can request the input');
}
`
Please solve this issue
I want to update the post
If you are using the route() helper in your form. You can pass the parameter using it :
<form action="{{ route('blog.update', ['post' => $post_id]) }}">...</form>
which is the post is the parameter you name in the route.
Since you haven't posted your blade file so here's the full method:
in your route:
Route::put('/blog/{post}/update' , [BlogController::class, 'update']);
in your blade form make tag like this:
<form method="post" action="/blog/{{$post->id}}/update">
//This will show url like /blog/1/update
//For using PUT method add this:
{{ method_field('PUT') }}
// Do not forget to use #csrf
Then in your controller update function handle the request and $id like this:
public function update(Request $request, $id){
//Find post in your data with help of model
$post = \App\Models\Post::findOrFail($id);
//validate and update with the post instance of Post class
//Feel free to add many functions same as of your controller before i'm leaving empty
$post->update([
//Add fields for update
]);
}

I want to use images of products that I register in the database - Laravel

I programmed a product registration. The registration for the database is working correctly. My problem is that I can't show the images that I registered in the database. I created an imput where the name of the image is inserted. This name is saved in the database and the image is saved with the same name, however it is saval in public. The images are inside the public / storage / products folder.
Controller:
public function index()
{
$products = Product::paginate(10);
return view('products.index', [
'products' => $products,
]);
}
public function store(Request $request)
{
// Create registration
$data = $request->only('name', 'price', 'imageName');
Product::create($data);
// Image
if($request->file('imageProduct')->isValid()){
$nameFile = $request->imageName . '.' . $request->file('imageProduct')->getClientOriginalExtension();
$request->file('imageProduct')->storeAs('products', $nameFile);
return redirect()->route('ProductControllerIndex');
}
}
view:
<div>
#foreach ($products as $product)
<p>
Id: {{ $product->id }}
</p>
<p>
Nome do produto: {{ $product->name }}
</p>
<p>
Preço: {{ $product->price }}
</p>
<p>
{{ $product->imageName }}
</p>
<p>
<img src="{{ asset('storage/products/'.$product->imageName) }}" alt="">
</p>
<hr>
#endforeach
</div>
The core issue here is that your Image's extension is not being saved to the database, so $product->imageName, when used in the asset() helper, doesn't generate a complete URL for the image. You'll need to refactor your code a little to get it to save:
public function store(Request $request) {
$nameFile = $request->input('imageName', '');
if($request->file('imageProduct')->isValid()){
$nameFile .= '.' . $request->file('imageProduct')->getClientOriginalExtension();
$request->file('imageProduct')->storeAs('products', $nameFile);
}
$request->merge(['imageName' => $nameFile]);
$data = $request->only('name', 'price', 'imageName');
Product::create($data);
return redirect()->route('ProductControllerIndex');
}
In the above code, the value for $nameFile is defaulted to the value in $request->input('imageName'), or an empty string '' if nothing is supplied. Next, if a valid image is uploaded, the $nameFile variable is appended with the extension. Lastly, the $request variable is updated with the name value for imageName. The remainder of the code creates the new Product with the data supplied (using the ->only() modifier) and redirect as required.
The rest of your code should be ok, as long as the file exists in the correct directory after ->storeAs() and the fully-qualified image name is saved to the database.
Note: If for whatever reason Product::create() doesn't work with this approach, you can use the new Product() ... $product->save() approach: (there might be an issue with $request->merge() using an existing key, as I can't actually test that)
$product = new Product();
$product->name = $request->input('name');
$product->price = $request->input('price');
$product->imageName = $fileName;
$product->save();

Uploading files with infyom generator

I am trying to upload a file with laravel using the code generated by the infyom generator. The file seems to be uploaded but this is what is shown on the application when I view the report (C:\xampp\tmp\php7925.tmp). Provided below is the code for my application.
Thank you so much and really appreciate the help in this project.
rgds,
Form
<!-- Inf File Field -->
<div class="form-group col-sm-6">
{!! Form::label('inf_file', 'Attachments:') !!}
{!! Form::file('inf_file') !!}
</div>
Controller
{
$input = $request->all();
$infrastructure = $this->infrastructureRepository->create($input);
$file = $request->file('inf_file');
$file = $request->inf_file;
if ($request->hasFile('inf_file')){
//
if ($request->file('inf_file')->isValid()){
}
}
Flash::success('Infrastructure saved successfully.');
return redirect(route('infrastructures.index'));
}
This is how you display when you view your records,
<!-- Inf File Field -->
<div class="form-group">
{!! Form::label('inf_file', 'Attachements:') !!}
<a download href="{{ asset($infrastructure->inf_file) }}">Download</a>
</div>
Managed to solve it.
public function store(CreateinfrastructureRequest $request)
{
$input = $request->all();
if ($request->hasFile('inf_file')){
//Validate the uploaded file
$Validation = $request->validate([
'inf_file' => 'required|file|mimes:pdf|max:30000'
]);
// cache the file
$file = $Validation['inf_file'];
// generate a new filename. getClientOriginalExtension() for the file extension
$filename = 'Infras-' . time() . '.' . $file->getClientOriginalExtension();
// save to storage/app/infrastructure as the new $filename
$InfrasFileName = $file->storeAs('infrastructure', $filename);
$path = "/storage/app/public/".$InfrasFileName;
}
$input['inf_file'] = $path;
$infrastructure = $this->infrastructureRepository->create($input);
Flash::success('Infrastructure saved successfully. ' . $path);
return redirect(route('infrastructures.index'));
}

How to upload an image using Laravel?

The problem:
I want to upload an image to a mySQL database using Laravel.
what I have tried:
I looked for other stack-overflow questions but they weren't helpful.
the result I am expecting :
is to have the image name or path saved to a column in my table on the database , to retrieve and display it later as a post in a blog.
First you need the form on your view (don't forget the csrf token):
<form action="/image-upload" method="POST" enctype="multipart/form-data">
#csrf
<input type="file" name="image">
<button type="submit">Upload</button>
</form>
And on your routes file add the route for POST method:
Route::post('image-upload', 'ImageUploadController#imageUploadPost');
Then on your Controller create the function that will validate and move your image to the 'public/images' folder.
public function imageUploadPost()
{
request()->validate([
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$imageName = time().'.'.request()->image->getClientOriginalExtension();
request()->image->move(public_path('images'), $imageName);
}
For better solution please read this: Laravel File Storage
Actually with Laravel it only involves a few lines of code. Let's say you have a user that has an avatar which is stored in the database. Here's how you would store and retrieve the avatar from the database:
1. First you'll need to have an avatar column in the users table that can store binary data. Depending on how large you want to allow the avatar image to be, the data type of the column can be one of the following:
BLOB up to 64KB
MEDIUMBLOB up to 16MB
LONGBLOB up to 4GB
2. To store the uploaded image in the database you can do this:
Route::post('user/{id}', function (Request $request, $id) {
// Get the file from the request
$file = $request->file('image');
// Get the contents of the file
$contents = $file->openFile()->fread($file->getSize());
// Store the contents to the database
$user = App\User::find($id);
$user->avatar = $contents;
$user->save();
});
3. To fetch and ouput the avatar you can do the following:
Route::get('user/{id}/avatar', function ($id) {
// Find the user
$user = App\User::find(1);
// Return the image in the response with the correct MIME type
return response()->make($user->avatar, 200, array(
'Content-Type' => (new finfo(FILEINFO_MIME))->buffer($user->avatar)
));
});
NOTE: Please have this in your mind, MySQL isn't a suitable solution to store BLOB. You may need to use an object storage service like Amazon S3.
Use this to upload image
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
// $this->validate($request,[//'movie_name'=>'required',
// // 'description'=>'required',
// //'video_url'=>'required',
// 'image'=>'required|mimes:jpeg,jpg,png,gif|required|max:10000',
// ]);
if ($request->hasFile('image') && $request->hasFile('image2')) {
$file = $request->file('image');
//$image=$file->getClientOriginalName();
$image = time().'.'.$file->getClientOriginalExtension();
$destinationPath ='assets/admin/uploads/image/';
$file->move($destinationPath,$image);
//echo $destinationPath;exit();
//echo $image."<br/>";
$file2 = $request->file('image2');
$bg_images = time().'.'.$file2->getClientOriginalExtension();
//$bg_images=$file2->getClientOriginalName();
$destinationPath ='assets/admin/uploads/bg_images/';
$file2->move($destinationPath,$bg_images);
$insert_data=array('movie_name'=>$request->movie_name,
'description'=>$request->description,
'video_url'=>$request->video_url,
'image'=>$image,
'bg_images'=>$bg_images,
'created_at'=>now(),
'updated_at'=>now()
);
//print_r($insert_data);exit();
}
else
{
if ( $request->hasFile('image2')) {
$file2 = $request->file('image2');
$bg_images = time().'.'.$file2->getClientOriginalExtension();
//$bg_images=$file2->getClientOriginalName();
$destinationPath ='assets/admin/uploads/bg_images/';
$file2->move($destinationPath,$bg_images);
//echo $destinationPath;exit();
//echo $bg_images;
$insert_data=array('movie_name'=>$request->movie_name,
'description'=>$request->description,
'video_url'=>$request->video_url,
//'image'=>$image,
'bg_images'=>$bg_images,
'created_at'=>now(),
'updated_at'=>now()
);
//print_r($insert_data);exit();
}
if ($request->hasFile('image') ) {
$file = $request->file('image');
//$image=$file->getClientOriginalName();
$image = time().'.'.$file->getClientOriginalExtension();
$destinationPath ='assets/admin/uploads/image/';
$file->move($destinationPath,$image);
//echo $destinationPath;exit();
//echo $image."<br/>";
$insert_data=array('movie_name'=>$request->movie_name,
'description'=>$request->description,
'video_url'=>$request->video_url,
'image'=>$image,
//'bg_images'=>$bg_images,
'created_at'=>now(),
'updated_at'=>now()
);
// print_r($insert_data);exit();
}
if ( ! $request->hasFile('image2') && ! $request->hasFile('image') ) {
$insert_data=array('movie_name'=>$request->movie_name,
'description'=>$request->description,
'video_url'=>$request->video_url,
//'image'=>$image,
// 'bg_images'=>$bg_images,
'updated_at'=>now()
);
// print_r($update_data);exit();
}
}
//exit();
// echo $image;
//exit();
//print_r($insert_data);exit();
$insert=DB::table('movies')->insert($insert_data);
if ($insert) {
return redirect()->route('admin.list_movies')->withSuccess('Record saved');
}
else {
return redirect()->route('admin.list_movies')->withError('Record not saved');
}
}

How to pass id to controller in laravel 5.2

I using this method to upload the image and passing the page id so i can store the path into database but having error "Missing argument 2 for App\Http\Controllers\RoundtablesController::postImage()"
This is my form
<div class="btn-group">
{!! Form::open(array('action' => 'RoundtablesController#postImage',$tables->id, 'files'=>true)) !!}
<div class="form-group">
{!! Form::label('Profile-Picture', 'Profile Picture:') !!}
{!! Form::file('profile_image',null,['class'=>'form-control']) !!}
</div>
<div class="form-group">
{!! Form::submit('Save', ['class' => 'btn btn-primary form-control']) !!}
</div>
{!! Form::close() !!}
</div>
This is my route
Route::post('/roundtables/settings',['uses'=>'RoundtablesController#postImage','middleware'=>['auth']]);
This is my controller ,the $name should get the Page Id, but look like the id not passed to here yet
public function postImage(Request $request,$name){
$table_details =Detail::find($name);
//save image
if ($request->hasFile('profile_image')) {
//add new photo
$image = $request->file('profile_image');
$filename = time() . '.' . $image->getClientOriginalExtension();
$location = public_path('images/' . $filename);
Image::make($image)->resize(800, 400)->save($location);
$oldFilename = $table_details->profile_image;
//update database
$table_details->profile_image = $filename;
//Delete old image
Storage::delete($oldFilename);
}
$table_details->update();
Can i know where is the error? Sry i know this is very basic but i am new in laravel.
Route:
Route::post('/roundtables/settings/{id}',
['as' => 'roundtables.setting',
'middleware'=>['auth'],
'uses'=>'RoundtablesController#postImage']);
Action:
public function postImage(Request $request, $id) {
$Detail = Detail::findOrFail($id); // will return 404 or exception if record not found
if ($request->hasFile('profile_image')) {
$file = $request->file('profile_image');
$profile_image = time() . '.' . $file->getClientOriginalExtension();
$profile_image_file = public_path('images/' . $profile_image);
Image::make($image)
->resize(800, 400)
->save($profile_image_file);
$old_profile_image_file = public_path('images/'.$Detail->profile_image);
if(is_file($profile_image_file)) { // if new file successfully created
$Detail->profile_image = $profile_image; // changing profile_image
$Detail->save(); // saving
Storage::delete($old_profile_image_file);
}
}
}
in view open form like (use named route: roundtables.setting defined in router):
{!! Form::open(array('url' => route('roundtables.setting', $tables->id), 'files'=>true)) !!}
also it's a little bit strange $tables->id, are You sure that $tables is an instance of model (not an array or collection) ?
route should be like
Route::post('/roundtables/settings/{name}',['uses'=>'RoundtablesController#postImage','middleware'=>['auth']]);
Try this way...
Route::get('groups/(:any)', array('as' => 'group', 'uses' => 'groups#show'));
class Groups_Controller extends Base_Controller {
public $restful = true;
public function get_show($groupID) {
return 'I am group id ' . $groupID;
}
}

Resources