Image uploading in laravel 5.8 - php

I am a beginner in laravel. i need to upload an image and that image needs to saved in the database but it is not working Could somebody take a look at my logic and see where I'm going wrong?
StudentController.php
public function store(Request $request)
{
$this->validateRequest();
// Handle File Upload
if($request->hasFile('cover_image')){
// Get filename with the extension
$filenameWithExt = $request->file('cover_image')->getClientOriginalName();
// Get just filename
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
// Get just ext
$extension = $request->file('cover_image')->getClientOriginalExtension();
// Filename to store
$fileNameToStore= $filename.'_'.time().'.'.$extension;
// Upload Image
$path = $request->file('cover_image')->storeAs('public/cover_images', $fileNameToStore);
} else {
$fileNameToStore = 'noimage.jpg';
}
dd( $fileNameToStore);
$student = new student();
$student->cover_image = $fileNameToStore;
$student->save();
return redirect()->route('show')->with('response', 'Registered Successfully');
}
when dd( $fileNameToStore); it is giving the result as "noimage.jpg"
create.blade.php
#extends('layouts.app')
#section('content')
<div class="container">
{!! Form::open(['url' => 'student','method' => 'get', 'enctype' => 'multipart/form-data'])!!}
<div class="form-group">
{{Form::file('cover_image')}}
</div>
<button type="submit" class="btn btn-primary">Submit</button>
{!! Form::close() !!}
</div>
#endsection

Related

Fetch image variable and display on input file

I am trying to update an image and other data in a database, but when I update only text data, the image value becomes null or empty.
<form action="/admin/settings/why-us/update/{{$data->id}}" enctype="multipart/form-data" method="POST">
#csrf
<input type="text" class="form-control" name="title" value="{{$data->title}}">
<input type="file" class="form-control" value="{{$data->image}}" name="image">
<button type="submit" class="btn btn-success py-2 px-4 text-white">Update changes</button>
</form>
This a controller
public function updateWhyusPageSetting(Request $request,$id)
{
$title = $request->input('title');
$image = $image = $request->file('image');
dd($image);
if($request->hasFile('image')) {
$image = $request->file('image');
$filename = $image->getClientOriginalName();
$image->move(public_path('/frontend/images/'), $filename);
$image_upload = $request->file('image')->getClientOriginalName();
}
DB::table('features')
->where('id', $id)
->update([
'title' => $title,
'image' => $image_upload
]);
\Session::flash('flash_message', __('Why us data updated'));
\Session::flash('flash_type', 'success');
return redirect()->back();
}
When I input only the title, left out the image, and tried to dump using dd($image);, I got a null value.
When updating the image, it's getting updated very well database.
Now, my question is, how do I make sure the value is captured in the input file <input type="file" class="form-control" value="{{$data->image}}" name="image"> so that when I update other data, it also sends the image value. NB: value="{{$data->image}}" IS NOT capturing the data from database
Try this code
public function updateWhyusPageSetting(Request $request,$id){
$data = [];
$data['title'] = $request->input('title');
if($request->hasFile('image')) {
$image = $request->file('image');
$image->move(public_path('/frontend/images/'),$imageName = $image->hashName()); //hashName() will generate image name with extension
$data['image'] = $imageName; // here if user uploads an image, it will add to data array then add to DB.
}
DB::table('features')
->where('id', $id)
->update($data); // if a user uploaded an image will add. if not, a previous image will not change
\Session::flash('flash_message', __('Why us data updated'));
\Session::flash('flash_type', 'success');
return redirect()->back();
}
Please note you should delete the old images if you don't need anymore
you can use this to delete an old image if you want
(new Filesystem())->delete("full/path/with/image/name.jpg");

Laravel - Image Array Validation gives an Error to nullable validate

I need to validate my image array as an image and specific image file extensions only. but my request validation to image WONT ALLOW me to use inser nullable values
For example I will add a content and dont want to add images. then the image should contain null that is why i need to have request validation as nullable. But in my experience null value is not allowed and it gives me error why? help me please
here is the error.
The Promotion Image must be an Image
here is my CONTROLLER
public function store(Request $request)
{
$this->validate($request, [
'promotion_image' => 'image|nullable|max:1999'
]);
$promotion = [];
if ($request->has('promotion_image'))
{
//Handle File Upload
foreach ($request->file('promotion_image') as $key => $file)
{
// Get FileName
$filenameWithExt = $file->getClientOriginalName();
//Get just filename
$filename = pathinfo( $filenameWithExt, PATHINFO_FILENAME);
//Get just extension
$extension = $file->getClientOriginalExtension();
//Filename to Store
$fileNameToStore = $filename.'_'.time().'.'.$extension;
//Upload Image
$path = $file->storeAs('public/promotion_images',$fileNameToStore);
array_push($promotion, $fileNameToStore);
}
$fileNameToStore = serialize($promotion);
}
else
{
$fileNameToStore='noimage.jpg';
}
if (count($promotion)) {
$implodedPromotion = implode(' , ', $promotion);
$promotionImage = new Promotion;
$promotionImage->promotion_image = $implodedPromotion;
$promotionImage->save();
return redirect('/admin/airlineplus/promotions')->with('success', 'Image Inserted');
}
return redirect('/admin/airlineplus/promotions')->with('error', 'Something went wrong.');
}
here is my VIEW
{!! Form::open(['action'=>'Admin\PromotionsController#store', 'method' => 'POST','enctype'=>'multipart/form-data', 'name' => 'add_name', 'id' => 'add_name']) !!}
<div class="form-group">
<div class="table-responsive">
<table class="table table-bordered" id="dynamic_field">
<tr>
<td> {{ Form::file('promotion_image[]')}}</td>
<td>{{ Form::button('', ['class' => 'btn btn-success fa fa-plus-circle', 'id'=>'add','name'=>'add', 'style'=>'font-size:15px;']) }}</td>
</tr>
</table>
{{Form::submit('submit', ['class'=>'btn btn-primary', 'name'=>'submit'])}}
</div>
</div>
{!! Form::close() !!}
No need to add nullable attribute in the validation. just change your validation code like this
$this->validate($request, [
'promotion_image.*' => 'image|max:1999'
]);
If you need user must add image input then you can use required validation rule other wise you don't need such thing.
Above code forces user to add file of type image or nothing at all.
I hope you understand and if any explanation needed, feel free to ask.
You need to validate it as an array:
$validator = Validator::make($request->all(), [
'photos.profile' => 'required|image',
]);
Take a look laravel docs
you may want to combine it with sometimes which indicates that the current validation rules will apply only if the field is present.

Laravel - Request Validation to Image set as Nullable is not allowed and gives error why?

I need to validate my image array as an image and specific image file extensions only. but my request validation to image WONT ALLOW me to use inser nullable values
For example I will add a content and dont want to add images. then the image should contain null that is why i need to have request validation as nullable. But in my experience null value is not allowed and it gives me error why? help me please
here is the error.
Undefined variable: promotion
here is my CONTROLLER
public function store(Request $request)
{
$this->validate($request, [
'promotion_image' => 'image|nullable|max:1999'
]);
if ($request->has('promotion_image'))
{
//Handle File Upload
$promotion = [];
foreach ($request->file('promotion_image') as $key => $file)
{
// Get FileName
$filenameWithExt = $file->getClientOriginalName();
//Get just filename
$filename = pathinfo( $filenameWithExt, PATHINFO_FILENAME);
//Get just extension
$extension = $file->getClientOriginalExtension();
//Filename to Store
$fileNameToStore = $filename.'_'.time().'.'.$extension;
//Upload Image
$path = $file->storeAs('public/promotion_images',$fileNameToStore);
array_push($promotion, $fileNameToStore);
}
$fileNameToStore = serialize($promotion);
}
else
{
$fileNameToStore='noimage.jpg';
}
if (count($promotion)) {
$implodedPromotion = implode(' , ', $promotion);
$promotionImage = new Promotion;
$promotionImage->promotion_image = $implodedPromotion;
$promotionImage->save();
return redirect('/admin/airlineplus/promotions')->with('success', 'Image Inserted');
}
return redirect('/admin/airlineplus/promotions')->with('error', 'Something went wrong.');
}
here is my VIEW
{!! Form::open(['action'=>'Admin\PromotionsController#store', 'method' => 'POST','enctype'=>'multipart/form-data', 'name' => 'add_name', 'id' => 'add_name']) !!}
<div class="form-group">
<div class="table-responsive">
<table class="table table-bordered" id="dynamic_field">
<tr>
<td> {{ Form::file('promotion_image[]')}}</td>
<td>{{ Form::button('', ['class' => 'btn btn-success fa fa-plus-circle', 'id'=>'add','name'=>'add', 'style'=>'font-size:15px;']) }}</td>
</tr>
</table>
{{Form::submit('submit', ['class'=>'btn btn-primary', 'name'=>'submit'])}}
</div>
</div>
{!! Form::close() !!}
You need to declare $promotion = [] above if ($request->has('promotion_image')), not inside of it.
So:
public function store(Request $request)
{
$this->validate($request, [
'promotion_image' => 'image|nullable|max:1999'
]);
$promotion = [];
if ($request->has('promotion_image'))
{
//Handle File Upload
That is because your selecting file other than image in your form. See the following to restrict user to only upload images.
<input accept=".png, .jpg, jpeg" name="files[]" type="file" multiple>
Not sure but try once
'promotion_image' => 'nullable|mimes:jpeg,jpg,png,gif|max:1999'

Call to a member function getClientOriginalExtension() on a non-object error

I am trying to edit/update my image upload but I am getting "Call to a member function getClientOriginalExtension() on a non-object" error. please help
My controller:
public function update(Request $request, $id)
{
$lnkupdate=Request::all();
$links=Links::findorFail($id);
$file = Input::file('image');
$random_name = str_random(8);
$destinationPath = 'albums/';
$extension = $file->getClientOriginalExtension();
$filename=$random_name.'_link_logo.'.$extension;
$uploadSuccess = Input::file('image')->move($destinationPath, $filename);
ConsularGen::update(array(
'name'=>Input::get('name'),
'link' => Input::get('link'),
'image' => $filename,
));
}
View:
{!!Form::model($links,['method'=>'PATCH','action'=>['LinksController#update',$links->id]])!!}
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="form-group">
<label for="image">Select a logo</label>
{!!Form::file('image')!!}
</div>
<div class="form-goup">
{!!Form::label('name','Name')!!}
{!!Form::text('name',null,['class'=>'form-control'])!!}
</div>
<div class="form-goup">
{!!Form::label('link','Link')!!}
{!!Form::text('link',null,['class'=>'form-control'])!!}
</div>
<div class="form-group">
<button type="submit" class="btnbtn-default">Add</button>
</div>
{!!Form::close()!!}
Route:
Route::patch('admin/links/{id}/update','LinksController#update');
Uploading files requires the html form to specify enctype="multipart/form-data". If you don't have this, the file will not be uploaded, Input::file('image') will return null, and you'll get the error you're seeing.
The Laravel Form builder will add this to your form if you tell it that it needs to handle files. Add 'files' => true to your array in the form:
{!! Form::model($links, ['method'=>'PATCH', 'files' => true, 'action'=>['LinksController#update', $links->id]]) !!}
Once this is fixed, you'll also get this error if you don't actually select a file to be uploaded. You should wrap your file handing inside a check to hasFile. Something like:
public function update(Request $request, $id)
{
$lnkupdate=Request::all();
if (Input::hasFile('image')) {
$links=Links::findorFail($id);
$file = Input::file('image');
$random_name = str_random(8);
$destinationPath = 'albums/';
$extension = $file->getClientOriginalExtension();
$filename=$random_name.'_link_logo.'.$extension;
$uploadSuccess = Input::file('image')->move($destinationPath, $filename);
ConsularGen::update(array(
'name'=>Input::get('name'),
'link' => Input::get('link'),
'image' => $filename,
));
} else {
echo 'no file uploaded. oops.';
}
}
Your file has not uploaded successfully.
you are trying to run getClientOriginalExtension() on a null file thats's why you are getting this error

Jpeg upload - image is currupted, but still visible

I have a php image upload form.
the image gets to the server, but then the image ends up looking like this:
That is not a snake at all! I'm not doing anything special to the image, just uploading and naming it. The corruption is adding about 100% to the file size.
I am hoping that by seeing the image somebody will have a bright idea as to what is happening. Thanks!
I am using laravel, but a previous iteration of this question in that context provided no leads, so I am asking in the context of the image alone, to cast a wider net.
upload form:
{{ Form::open(array('url'=>'/manage/photos/upload', 'class'=>'form-signin', 'files' => true)) }}
{{ Form::file('image') }}
{{ Form::submit('Upload Photos', array('class'=>'btn btn-large btn-primary btn-block'))}}
{{ Form::close() }}
file receiving code in my controller:
public function uploadPhoto() {
$file = Input::file('image');
$input = array('image' => $file);
$rules = array(
'image' => 'image'
);
$validator = Validator::make($input, $rules);
if ( $validator->fails() )
{
return Redirect::to('/manage/photos')->with('message', 'There was a problem:');
} else {
$destinationPath = 'profileimages';
$filename = uniqid('', true).'.jpg';
Input::file('image')->move($destinationPath, $filename);
return Redirect::back()->with('message', 'The photo was successfully uploaded');
}
}

Categories