Mimes Validation not working correctly in Laravel 9 - laravel

My webpage contains a file for upload, and I want the file uploaded only to be either jpg, jpeg or png.
My HTML looks like this:
<div class="form-group">
<label for="autoSizingInput">Brand Image</label>
<input type="file" class="form-control" id="autoSizingInput" name="brand_image"
aria-describedby="emailHelp">
#error('brand_image')
<span class="text-danger"> {{ $message }}</span>
#enderror
</div>
for checking files I used:
$request->validate(
[
'brand_image' => 'required|mimes:jpg,jpeg,png'
]);
when I upload pdf files it shows an error but when I upload any gif file it doesn't show any error.

$rules = [
'brand_image' => 'required|mimes:jpeg,jpg,png,
];
$validator = Validator::make($request->all(), $rules);
$validator->validate();
Try something like this

Try this it should work
$Rules = [ 'brand_image' => 'required|mimes:jpg,jpeg,png',
];
$Validator = Validator::make($r->all(), $Rules);
if ($Validator->fails()) {
return back()->withErrors($Validator->errors()->all());
} else {
Code....
}

Related

Laravel Livewire Hook not firing for a multiple images

I am trying to upload images when the file field is updated but can't figure out why the UpdatedFoo method isn't fired,
<input type="file" class="custom-file-input" wire:model="photos"
multiple>
<label class="custom-file-label" for="customFile">Choose
image {{ $key + 1 }}</label>
My Livewire component
public $photos = [];
public function UpdatedPhotos($value, $key)
{
$this->validate([
'photos' => 'image|max:1024', // 1MB Max
]);
$storage = new Storage(config('kizusi.client'));
foreach ($this->photos as $photo) {
$result = $storage->createFile('tours', 'unique()', $photo);
print_r($result);
}
}
Alright, I got it,
The validation was preventing my images from being submitted
$this->validate([
'photos' => 'image|max:1024', // 1MB Max
]);

Laravel stored image is tmp not jpg when update data

When I update image the data stored is tmp, not an image file.
Here's my controller:
public function update(Request $request, $id)
{
$change = Post::findorfail($id);
$before = $change->image;
$post = [
'title' => $request['title'],
'tags_id' => $request['tags_id'],
'content' => $request['content'],
'image' => $before,
];
if($request->hasFile('image')){
$request->image->move(public_path().'/image', $before);
}
$change->update($post);
return redirect('post');
}
View:
<div class="form-group row mb-4">
<label class="col-form-label text-md-right col-12 col-md-3 col-lg-3">Featured Image</label>
<div class="col-sm-12 col-md-7">
<input type="file" name="image" class="form-control" value="{{ $data->image }}">
</div>
</div>
Thanks for your help
You must save request image file into system instead of moving old image file.
public function update(Request $request, $id)
{
$change = Post::findorfail($id);
$image = $request->hasFile('image')
? $request->photo->store('image', 'public')
: $change->image;
$post = [
'title' => $request['title'],
'tags_id' => $request['tags_id'],
'content' => $request['content'],
'image' => '/storage/' . $image,
];
$change->update($post);
return redirect('post');
}
This will save new image into /storage/public/image/ path. To make this address accessible through url, you must create a symlink from public path to storage path by running this:
php artisan storage:link
This will create a storage symlink in /public folder which points to /storage/public path. Read the complete documentation about this functionality here: https://laravel.com/docs/8.x/filesystem#the-public-disk

Laravel Form Request Validation error message bag contains empty value in view?

I have a Request file to validate the form. What I am encountering is that, I have at least 24 form fields to validate, but the problem is fields get validated and return back to the view, when validation fails. But the errors is not get sent to view.
But, I mentioned the rules for lets say only 6 fields, then the message is being displayed properly in the view.
I have done the research on stackoverflow, and tried every solutions, but none work for me.
use this type of dorm fields in your view
<div class="col-8 ml-auto">
<input id="serialNumber" type="text" class="form-control t-cap"
name="serialNumber" value="{{ $invoice->serialNumber }}">
</div>
#if ($errors->has('serialNumber'))
<span class="col-md-12 form-error-message">
<small for="serialNumber">{{ $errors->first('serialNumber') }}</small>
</span>
#endif
</div>
And in Your Controller use Like This
$rules = array(
'customer.mobile'=> 'required|regex:/\+91[[:space:]]\d{10}/',
'serialNumber' => 'required',
);
$validator = Validator::make($request->all(), $rules);
if ($validator->fails()) {
return Response::json(array(
'status' => 0,
'errors' => $validator->errors()
), 400);
}

Call to a member function getClientOriginalName() on null when upload image use file system Laravel

I want to upload an image using Laravel storage file system in my admin data. However, there's an error when I attempt to upload an image.
Call to a member function getClientOriginalName() on null
Controller
public function store(Request $request)
{
$admin = $request->all();
$fileName = $request->file('foto')->getClientOriginalName();
$destinationPath = 'images/';
$proses = $request->file('foto')->move($destinationPath, $fileName);
if($request->hasFile('foto'))
{
$obj = array (
'foto' => $fileName,
'nama_admin' => $admin['nama_admin'],
'email' => $admin['email'],
'jabatan' => $admin['jabatan'],
'password' => $admin['password'],
'confirm_password' => $admin['confirm_password']
);
DB::table('admins')->insert($obj);
}
return redirect()->route('admin-index');
}
View
<div class="form-group">
<label for="" class="col-md-4">Upload Foto</label>
<div class="col-md-6">
<input type="file" name="foto">
</div>
</div>
Error
You can check wheather you are getting file or not by var_dump($request->file('foto')->getClientOriginalName());
And make sure your form has enctype="multipart/form-data" set
<form enctype="multipart/form-data" method="post" action="{{ url('/store')}}">
<div class="form-group">
<label for="" class="col-md-4">Upload Foto</label>
<div class="col-md-6">
<input type="file" name="foto">
</div>
</div>
</form>
Error because of client Side
<form enctype="multipart/form-data" method="post" action="{{ url('/store')}}">
<div class="form-group">
<label for="" class="col-md-4">Upload Foto</label>
<div class="col-md-6">
<input type="file" name="foto">
</div>
</div>
</form>
you ned to add enctype="multipart/form-data" inside the form
If You are using the form builder version
{!! Form::open(['url' => ['store'],'autocomplete' => 'off','files' => 'true','enctype'=>'multipart/form-data' ]) !!}
{!! Form::close() !!}
Then In your Controller You can check if the request has the file
I have Created the simple handy function to upload the file
Open Your Controller And Paste the code below
private function uploadFile($fileName = '', $destinationPath = '')
{
$fileOriginalName = $fileName->getClientOriginalName();
$timeStringFile = md5(time() . mt_rand(1, 10)) . $fileOriginalName;
$fileName->move($destinationPath, $timeStringFile);
return $timeStringFile;
}
And the store method
Eloquent way
public function store(Request $request)
{
$destinationPath = public_path().'images/';
$fotoFile='';
if ($request->hasFile('foto'))
{
$fotoFile= $this->uploadFile($request->foto,$destinationPath );
}
Admin::create(array_merge($request->all() , ['foto' => $fotoFile]));
return redirect()->route('admin-index')->with('success','Admin Created Successfully');
}
DB Facade Version
if You are using DB use use Illuminate\Support\Facades\DB; in top of your Controller
public function store(Request $request)
{
$admin = $request->all();
$destinationPath = public_path().'images/';
$fotoFile='';
if ($request->hasFile('foto'))
{
$fotoFile = $this->uploadFile($request->foto,$destinationPath );
}
$obj = array (
'foto' => $fotoFile,
'nama_admin' => $admin['nama_admin'],
'email' => $admin['email'],
'jabatan' => $admin['jabatan'],
'password' => $admin['password'],
'confirm_password' => $admin['confirm_password']
);
DB::table('admins')->insert($obj);
return redirect()->route('admin-index');
}
Hope it is clear

Adding the file name uploaded to the Laravel validation message

I have an array of files being uploaded. In the validation.php language file I've added custom error messages:
'custom' => [
'images.*' => [
'dimensions' => 'Image ":file" must have a min-height of :min_height pixels and a min-width of :min_width pixels.',
'image' => 'You can only upload images to your gallery. The file ":file" was not an image.',
'mimes' => 'Your image ":file" was an invalid type. Images can only be of the following types: :mimes',
'max' => 'Max file size for each image is :max MB. Your image ":file" is too large.'
]
]
Since there are multiple files being uploaded, I would like to be able to specify which file the error message relates to when I display the validation errors.
#if($errors->has('images.*'))
#foreach ($errors->get('images.*') as $message)
<div class="help-block has-error">{{ head($message) }}</div>
#endforeach
#endif
However, :file is not auto filled in the message and I don't know how to get it.
How would I go about doing this? Is there another placeholder or method I can use?
I have the same issue, what I try to do is to get names of files in an array and put it in custom error message depend on validation type in my example, I will get file name depend on image type (jpeg, png, jpg, SVG, BMP)
In controller file:
//...
public function store(Request $request)
{
$rules = [ 'imagefile' => 'required',
'imagefile.*' => 'image|mimes:jpeg,png,jpg,svg,bmp', // working on filse size custom message
];
// To get name of non image file and display in it in error message
if($request->hasfile('imagefile')){
$names = array(); // array for all names of files
foreach($request->Bank_Logo as $file){
// check file extension
if($file->getClientOriginalExtension() != 'jpeg' &&
$file->getClientOriginalExtension() != 'png' &&
$file->getClientOriginalExtension() != 'jpg' &&
$file->getClientOriginalExtension() != 'svg' &&
$file->getClientOriginalExtension() != 'bmp'){
$name= $file->getClientOriginalName (); // get file name
$names[] = $name; // set name of file to array
}
}
// check names array if it empty or not
if(!empty($names)){
/* but all names in custom error,message
* implode funaction to convert array to string
*/
$messages = [
'imagefile.*image' => 'The ' . implode(" and ",$names) . ' not an image file.',
'imagefile.*mimes' => 'The ' . implode(" and ",$names) . ' must be a file of type: jpeg, png, jpg, svg, bmp.'
];
}
}
if(!empty($messages)){
$result = Validator::make($request->all(), $rules, $messages); // with custom message
//dd($result);
}
else{
$result = Validator::make($request->all(), $rules); // without custom message
//dd('empty');
}
if($result->fails())
{
return back()->withErrors($result)->withInput($request->all());
}
dd($request->all());
//...
}
In balde file
//...
<form>
label class="form-control-label mt-3">{{ __('imagefileLogo') }}</label>
<div class="file-loading">
<input id="imagefile" name="imagefile[]" type="file" multiple>
</div>
#if ($errors->has('imagefile'))
<span class="invalid-feedback" style="display: block;" role="alert">
<strong>{{ $errors->first('imagefile') }}</strong>
</span>
#endif
#if ($errors->has('imagefile.*')) <!--in case if we have multiple file-->
<span class="invalid-feedback" style="display: block;" role="alert">
<strong>{{ $errors->first('imagefile.*') }}</strong>
</span>
#endif
<form>
//...
Same thing you can do with file size.
Also, I use [this plugin] for upload file input
[this plugin]: https://plugins.krajee.com/file-input#top
Laravel version 5.8
I hope this was helpful to you.
if anyone has a better way please discuss.

Resources