laravel livewire Save file using file name - laravel

I'm trying to save uploaded pdf files but the pdf file name changes on the storage link. is there any way to retain the original file name when saving?
public $code, $pdfs;
public function mount(Applicant $applicant)
{
$this->code = substr(str_shuffle(str_repeat("ABCDEFGHIJKLMNOPQRSTUVWXYZ", 5)), 0, 3).Carbon::createFromFormat('Y-m-d H:i:s', now())->format('md').rand(100, 999);
}
public function submit(Request $request)
{
$this->validate([
'pdfs.*' => 'mimes:pdf',
]);
$filenames = collect($this->tests)->map->store($this->code.'/', 'public');
return redirect()->route('careers.vacant');
}
here's my blade
<form wire:submit.prevent="submit" class="pt-3" enctype="multipart/form-data">
<div class="form-group">
<label class="form-label required" for="code" >Application {{ trans('fields.code') }}</label>
<input class="form-control" type="text" name="code" id="code" wire:model.defer="code" >
<div class="validation-message">
{{ $errors->first('code') }}
</div>
<div class="help-block">
{{ trans('fields.code_helper') }}
</div>
</div>
<input type="file" name="pdf" id="pdf" wire:model="pdfs" multiple >
<div wire:loading wire:target="pdfs">Uploading...</div>
#error('pdfs.*') <span class="error">{{ $message }}</span> #enderror
<div class="form-group">
<button class="mr-2 btn btn-indigo" type="submit">
{{ trans('global.submit') }}
</button>
<a href="{{ route('admin.applicants.index') }}" class="btn btn-secondary">
{{ trans('global.cancel') }}
</a>
</div>
</form>
I need to save the pdfs like this:
$filenames = collect($this->tests)->map->store($this->code.'/'.pdfFileName, 'public');
EDIT:
foreach ($this->tests as $file) {
$name = $file->getClientOriginalName();
$file->store('moca/'.$this->code.'/'.$name, 'public');
}
I tried this code but in the path $name becomes a folder instead of becoming the name of the file

You can try this:
$request->file('pdf')->getClientOriginalName() will return the original name of file

Related

Can't store Files in public folder in Laravel 8

i'm trying to store pdf, txt... in DB
but i get this error:
Method Illuminate\Validation\Validator::validateCsv,txt,xlx,xls,pdf does not exist.
but when i add required|mimes this error i get:
The file must be a file of type: pdf, xlx, csv, txt, doc.
here the code:
public function store(Request $request)
{
$validatedData = $request->validate([
'file' => 'required|mimes:pdf,xlx,csv,txt,doc'
]);
$name = $request->file('file')->getClientOriginalName();
$path = $request->file('file')->store('public/files');
$save = new File;
$save->name = $name;
$save->path = $path;
return redirect('file-upload')->with('status', 'File Has been uploaded successfully');
}
my blade code:
<body>
<div class="container mt-4">
<form method="post" enctype="multipart/form-data" id="upload-file" action="{{ url('store') }}" >
<div class="row">
<div class="col-md-12">
<div class="form-group">
<input type="file" name="file" placeholder="Choose file" id="file">
#error('file')
<div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
#enderror
</div>
</div>
<div class="col-md-12">
<button type="submit" class="btn btn-primary" id="submit">Submit</button>
</div>
</div>
</form>
</div>
</div>
</body>
how can i fix it?
Use File to put content
\File::put(public_path('storage'). '/public/files/'. $file);

laravel-5.8:Invalid argument supplied for foreach()

hi I make a form to upload pics in Laravel but when I open the form then it shows error: Invalid argument supplied for foreach()
blade file:
<form method="POST" action="{{ route('admin.product.alternateimages') }}" enctype="multipart/form-data" class="add-new-post">
#csrf
<strong class="text-muted d-block mb-2 mt-5">Upload Product Image</strong>
<div class="input-group mb-3">
<div class="input-group input-group-seamless">
<input type="file" name="product_alt_img[]" class="form-control mb-2 btn btn-sm btn-outline-primary mr-1 #error('product_image') is-invalid #enderror" value="{{ old('product_image') }}" id="" placeholder=""> </div>
#error('product_image')
<div class="small text-danger">{{ $message }}</div>
#enderror
</div>
</form>
function:
public function alternateimages(Request $request)
{
$altimgs = new Product;
$altimgs->product_id = $request->product_id;
$files = $request->file('product_alt_img');
foreach ($files as $file) {
$images = $file->getClientOriginalName();
$file->move(public_path('images/backend_images/product_images'), $images);
$altimgs->product_alt_img = $images;
}
$altimgs->save();
return redirect()->back()->with('flash_message_success', 'Product Images has been added successfully');
}
You may have to change product_alt_img[] to product_alt_img if you are uploading a single file.
<input type="file" name="product_alt_img" class="form-control mb-2 btn btn-sm btn-outline-primary mr-1 #error('product_image') is-invalid #enderror" value="{{ old('product_image') }}" id="" placeholder="">
Else if wish to upload multiple file, you may have to modify your controller method.
public function alternateimages(Request $request)
{
$altimgs = new Product;
$altimgs->product_id = $request->product_id;
//fetch an array of product_alt_img
$files = $request->product_alt_img;
//go over each Illuminate\Http\UploadedFile instance
foreach($files as $file)
{
$image = $file->getClientOriginalName();
....
}
....
}
NB: A more eloquent solution is to have a separate table for storing products images

How to edit image and update in laravel

I have a table called Services, now this table has the following -
-id
-title
-body
-image
-slug
-timestamps
And in administrator, services page I created for Add, Edit, Delete it.
My problem is edit and update a image. A strange problem is that, when I change the of image to aaaaa field in the service table (database), Nothing happens. should happen. because I changed rename of image to aaaaa.
web.php
Route::resource('services', 'ServiceController');
ServiceController.php
public function edit(Service $service)
{
return view('Admin.services.edit', compact('service'));
}
public function update(Request $request, Service $service)
{
$service->title = $request->title;
$service->body = $request->body;
if($request->has('image')) {
$image = $request->file('image');
$filename = $image->getClientOriginalName();
$image->move(public_path('images/services'), $filename);
$service->image = $request->file('image')->getClientOriginalName();
}
$service->update();
return redirect()->route('services.index');
}
edit.blade.php
<form class="form-horizontal" action="{{ route('services.update', $service->id) }}" method="post" enctype="multipart/form-data">
{{ csrf_field() }}
{{ method_field('PATCH') }}
#include('Admin.layouts.errors')
<div class="form-group">
<label for="title">عنوان</label>
<input type="text" class="form-control" id="title" name="title" placeholder="عنوان" value="{{ $service->title ? : old('title') }}">
</div>
<div class="form-group">
<label for="body">متن</label>
<textarea class="form-control" rows="10" id="body" name="body" placeholder="متن">{{ $service->body ? : old('body') }}</textarea>
</div>
<div class="form-group">
<label for="images">تصویر</label>
<div class="custom-file">
<input type="file" class="custom-file-input" id="images" name="images">
<label class="custom-file-label" for="images">تصویر محصول</label>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">ذخیره</button>
</div>
</form>
Service.php
protected $fillable = [
'title',
'body',
'image',
'slug',
];
I even changed the controller in the update method as follows, nothing happened.
$service->save();
I think one of efficient way to edit image in laravel.
add this at top of the controller
use File;
First of get your bannerId in a variable
$bannerId = $request->banner_id;
get object of that id by find ().
$bannerData = FrontEndBanner::find($bannerId);
check if file exist and check if file already exist then delete that file else same name will inserted in imageName variable
if ($request->hasFile('banner_image')){
$image_path = public_path("/uploads/resource/".$bannerData->banner_name);
if (File::exists($image_path)) {
File::delete($image_path);
}
$bannerImage = $request->file('banner_image');
$imgName = $bannerImage->getClientOriginalName();
$destinationPath = public_path('/uploads/resource/');
$bannerImage->move($destinationPath, $imgName);
} else {
$imgName = $bannerData->banner_name;
}
$bannerData->title = $request->banner_title;
$bannerData->banner_name = $imgName;
$bannerData->save();
If anyone have issue then comment
In the html you have:
<input type="file" class="custom-file-input" id="images" name="images">
and in Controller: $request->file('image').
Replace
<input type="file" class="custom-file-input" id="images" name="images">
with
<input type="file" class="custom-file-input" id="images" name="image">

Update image in laravel won't work

I'm trying to update image in my laravel project but it won't save the image, I'm using intervention package
this is the result i use dd
Controller:
public function update(Request $request, $id)
{
//
$this->validate($request, [
'student_name'=>'required|max:50',
'lead_status'=>'required|max:50',
'lead_source'=>'required|max:50',
'avatar' =>'image',
]);
$leads = Lead::findOrFail($id);
$leads->student_name = $request->student_name;
$leads->student_nric = $request->student_nric;
$leads->gender = $request->gender;
$leads->religion = $request->religion;
$leads->race = $request->race;
$leads->date_of_birth = $request->date_of_birth;
$leads->Address = $request->Address;
$leads->last_school_attended= $request->last_school_attended;
$leads->last_grade_completed = $request->last_grade_completed;
$leads->grade_appliying = $request->grade_appliying;
if($request->hasFile('avatar')){
$image=$request->file('avatar');
$filename=time() . '.' . $image->getClientOriginalExtension();
$location=public_path('images/' .$filename);
Image::make($image)->resize(300, 300)->save($location);
$leads->image=$filename;
$leads->save();
}
else{
$leads->save();
session()->flash('notif','Application Saved Successfully');
return view('leads.edit')->with('leads', $leads);
}
}
Edit.Blade View
<div class="row">
<div class="col-sm-4 form-group">
<img src="/uploads/avatars/{{$leads->image}}" style="width:150px;height:150px;border-radius:50px;">
<form enctype="multipart/form-data" action="{{route('leads.update', $leads->id)}}" method="POST" >
{{ csrf_field() }}
{{ method_field('PUT') }}
<label> Upload Image</label>
<input type="file" name="avatar">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
</div>
<div class="col-sm-12">
<h4 text-muted>CHILD'S INFORMATION</h3>
<hr>
<div class="row">
<div class="col-sm-4 form-group">
<label>FULLNAME</label>
<input class="form-control" style="text-transform: uppercase;" type="text" name="student_name" value="{{$leads->student_name}}" placeholder="Enter FULLNAME.." autocomplete="off">
</div>
Note: i will always end up null value on my image please point me to a correct tutorial if u have..
......................................................................................................................................
Add a hidden input type with your database variable in your edit blade
and put the value of your hidden input name in else condition to save.
<input type="hidden" name="old_image_name"
value="#if(isset($admin_details)){{$admin_details->image}} #endif"/>

Laravel The picture failed to upload

I'm working on a Laravel 5.4 app and the picture I try to upload is not moving to my disk.
Could you help me ?
My form:
<form class="form-horizontal" role="form" method="POST" action="{{ route('adminPostNews') }}" accept-charset="UTF-8" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="form-group{{ $errors->has('picture') ? ' has-error' : '' }}">
<label for="picture" class="col-md-1 control-label">Photo</label>
<div class="col-md-6">
<input type="file" id="picture" name="picture">
#if ($errors->has('picture'))
<span class="help-block">
<strong>{{ $errors->first('picture') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary">
Ajouter
</button>
</div>
</div>
</form>
Controller:
public function store_actualites(Request $request)
{
$this->validate($request, [
'picture' => 'required|mimes:jpeg']);
if($request->file('picture'))
{
$file = $request->file('picture');
$extension = $file->getClientOriginalExtension();
Storage::disk('news')->put($file->getFilename().'.'.$extension, File::get($file));
}
}
My disk is ok, Laravel is giving the name of the file but the upload wont works.
You are not passing correctly the file name, try this:
//Save image
if ($request->hasFile('picture')) {
$file = $request->file('picture');
$fileName = $file->getClientOriginalName();
Storage::disk('news')->put($fileName, File::get($file));
}
ok, maybe the first answer will be: server file upload size limit !
Second, here is my new code:
$file = $request->file('picture');
$extension = $file->getClientOriginalExtension();
Storage::disk('news')->put($file->getFilename().'.'.$extension, file_get_contents($file));
I failed to use something different of "file_get_contents".

Resources