Can't store Files in public folder in Laravel 8 - laravel

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);

Related

Why upload image fails using Laravel 9 CRUD?

I am creating a database for books. When I was testing CRUD without image upload(normal CRUD), it was working. But when I added book cover image file as part of data input I get error "
Argument #1 ($rules) must be of type array, Illuminate\Http\Request given, called in
". I didn't understand what caused it, is it because validation or path image folder will be stored in?
Here it is image of error.
Model/Buku.php
class Buku extends Model
{
use HasFactory;
protected $fillable = [
'cover',
'nama_buku',
'author',
'terbitan',
'barcode',
'ketersediaan',
];
}
I suspect the error is in controllers code but didn't know why normal CRUD succeed but image upload CRUD fails.
Controllers/BukuController.php
protected function store(Request $request)
{
$request->validate($request, [
'cover' => 'required|file|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
'nama_buku' => 'required',
'author' => 'required',
'terbitan' => 'required',
'barcode' => 'required',
'ketersediaan' => 'required',
]);
$input = $request->all();
if ($cover = $request->file('cover')) {
$destinationPath = 'cover/';
$profileImage = date('YmdHis') . "." . $cover->getClientOriginalExtension();
$cover->move($destinationPath, $profileImage);
$input['cover'] = "$profileImage";
}
Buku::create($input);
return redirect()->route('buku.index')->with('success','Buku has been created successfully.');
}
I don't know if the errors is actually from input so just in case here is views create blade
Views/create.blade.php
<form action="{{ route('buku.store') }}" method="POST" enctype="multipart/form-data">
#csrf
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Cover:</strong>
<input type="file" name="cover" placeholder="Cover Buku"
class="block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100" />
#error('cover')
<div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
#enderror
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Nama Buku:</strong>
<input type="text" name="nama_buku" class="form-control" placeholder="Nama Buku">
#error('nama_buku')
<div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
#enderror
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Author:</strong>
<input type="text" name="author" class="form-control" placeholder="Author Buku">
#error('author')
<div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
#enderror
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Terbitan:</strong>
<input type="text" name="terbitan" class="form-control" placeholder="Terbitan Buku">
#error('terbitan')
<div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
#enderror
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Barcode:</strong>
<input type="text" name="barcode" placeholder="Barcode Buku" id="scanner" />
#error('barcode')
<div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
#enderror
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Ketersediaan:</strong>
<input type="number" name="ketersediaan" class="form-control" placeholder="Ketersediaan Buku">
#error('ketersediaan')
<div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
#enderror
</div>
</div>
<button type="submit" class="btn btn-primary ml-3">Submit</button>
</div>
</form>
I also tried image upload code when I was still using Laravel 4, still get the same error. Did anyone know how to fix this?
The error states it pretty clearly. You pass a Request object where an array is expected.
Instead of using the object directly, you should use the all() method, which creates an array with all the posted fields in your request. Or in this case, you can leave the request->all() out, because the method is already called on the request object.
$request->validate($request,...)
$request->validate($request->all(),...)
$request->validate(['cover' => ....])
#########EDIT
It is also not recommended to insert all request data. You should only insert validated data.
$input = $request->all();
Buku::create($input);
You should use one of the two following approaches to only insert validated data: https://laravel.com/docs/10.x/validation#working-with-validated-input

laravel livewire Save file using file name

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

I am trying to update multiple images but getting error using laravel 8

I am trying to update multiple images but unfortunately I am getting error please help me how can i resolved that ? thank u.
please check error
Invalid argument supplied for foreach()
controller
public function update(Request $request, $roomId)
{
if($request->has('images')){
foreach($request->file('images') as $value){
$extension = $value->getClientOriginalExtension();
Storage::disk('wfh')->put($value->getFilename() . '.' . $extension,
File::get($value));
$roomDetail->image = $value->getFilename() . '.' . $extension;
$roomDetail = RoomDetail::where('room_id',$roomId)->first();
$roomDetail->update([
'room_id' => $roomId,
'image' => $roomDetail->image,
]);
}
}
Html view
<form action="{{route('room.update',$editRooms->id)}}" method="POST" class="needs-validation"
novalidate enctype="multipart/form-data">
#csrf
#method('PUT')
<div class="row">
<div class="col-md-8">
<div class="input-field">
<label class="active">Images Upload</label>
<div class="input-images" style="padding-top: .5rem;" ></div>
#foreach ($roomDetails as $value)
<img height="100px" class="mt-4 m-4" width="100px" src="{{
Config('wfh.file')
.$value->image}}" alt="">
<input type="hidden" name="images[]" value="{{$value->image}}" >
#endforeach
</div>
</div>
</div>
<div class="col-md-3">
<div class="modal-footer">
<button type="submit" id="btnSubmit" class="btn btn-primary btn-lg w-100">Add
Room</button>
</div>
</div>
</form>

Upload multiple image files using 2 input file in Laravel

I want to upload multiple images using 2 input file fields in Laravel and put that 2 files to DB with different attributes (imagepath1, imagepath2). If I try that code there both input & upload the same file like imagekitchen2 (there both change but imagepath1 become imagepath2 and imagepath2 still imagepath2).
Controller
public function store(Request $request)
{
$kitchens = new Kitchen();
$kitchens->title = $request->input('title-kitchen');
$kitchens->description = $request->input('description-kitchen');
if ($request->hasfile('imagekitchen1')) {
$file = $request->file('imagekitchen1');
$extension = $file->getClientOriginalExtension();
$filename = time().'.'.$extension;
$file->move('uploads/product/kitchen/', $filename);
$kitchens->imagepath1 = $filename;
} else {
$kitchens->imagepath1 = '';
}
$kitchens->save();
if ($request->hasfile('imagekitchen2')) {
$file = $request->file('imagekitchen2');
$extension = $file->getClientOriginalExtension();
$filename = time().'.'.$extension;
$file->move('uploads/product/kitchen/', $filename);
$kitchens->imagepath2 = $filename;
} else {
$kitchens->imagepath2 = '';
}
$kitchens->save();
}
View
<div class="card-body">
<div class="row">
<div class="col-md-6">
<form action="{{ route('addimagekitchen') }}" enctype="multipart/form-data" method="POST">
{{ csrf_field() }}
<div class="form-group">
<label>Title</label>
<label>
<input type="text" name="title-kitchen" class="form-control">
</label>
</div>
<div class="input-group">
<div class="custom-file">
<label for="image" style="display: block">Main image</label> <br/>
<input type="file" name="imagekitchen1" style="margin-left: 20px">
</div>
</div>
<div class="input-group">
<div class="custom-file">
<label for="image" style="display: block">Second image</label> <br/>
<input type="file" name="imagekitchen2" style="margin-left: 20px">
</div>
</div>
<div class="input-group">
<div class="custom-file">
<label for="image" style="display: block">Third image</label> <br/>
<input type="file" name="imagekitchen[]" style="margin-left: 20px">
</div>
</div>
<div class="form-group">
<label>Description</label>
<textarea class="form-control" name="description-kitchen" id="description-kitchen"
rows="3"></textarea>
</div>
<button type="submit" class="btn btn-success"> Insert</button>
Cancel
</form>
</div>
</div>
</div>
I'm not completely sure what you mean, but probably you should change:
$kitchens->save();
if($request->hasfile('imagekitchen2')){
into
$kitchens->save();
$kitchens = new Kitchen();
if($request->hasfile('imagekitchen2')){
this way, you will create 2 records, otherwise you used same object and updated it after creation. Depending on your needs you might also want to add:
$kitchens->title = $request->input('title-kitchen');
$kitchens->description = $request->input('description-kitchen');
before:
if($request->hasfile('imagekitchen2')){
in case you want to save same title and description for both records.
Of course I'm not sure if you want to create records if there are no files - at the moment both will be saved in case no file uploaded.

updating image hasfile condition

Now i'm trying to update an image but in method update it keeps skip the hasfile condition
public function update(Request $request, $id)
{
$slider = Slider::find($id);
$slider->header = $request->header;
$slider->paragraph=$request->paragraph;
if($request->hasFile('image')){
return 'a';
// $image=$request->file('image');
// $filename=time(). '.' .$image->getClientOriginalExtension();
// $location=public_path('images/' . $filename);
// Image::make($image)->save($location);
// $oldFilename=$slider->image;
// $slider->image=$filename;
// File::delete(public_path('images/'. $oldFilename));
}else{
return 'whatever';
}
}
and here's my view
<form class="form-horizontal" action="{{ route('slider.update',$slider->id) }}" method="post" enctype="multipart/form-data">
{{ csrf_field() }}
{{method_field('PATCH')}}
<div class="row">
<div class="col-lg-12">
<div class="ibox float-e-margins">
<div class="ibox-title back-change">
<h5>الغلاف </h5>
</div>
<div class="ibox-content">
<div class="row">
<div class="col-md-6">
<div class="image-crop">
<img src="{{asset('images/'.$slider->image)}}">
</div>
</div>
<div class="col-md-6">
<div class="btn-group">
<label title="Upload image file" for="inputImage" class="btn btn-primary">
<input type="file" name="image" id="inputImage" class="hide">
Upload new image
</label>
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-2 col-lg-10">
<button class="btn btn-primary pull-right" type="submit"> حفظ التغيرات</button>
</div>
</div>
</div>
</div>
</div>
Why can I not get to the condition?
The form is okay and the name of the input is okay, but it still returns to else.

Resources