Update image in laravel won't work - laravel

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"/>

Related

Laravel : Call to a member function getClientOriginalName() on null when Update Data

I will update the data its contain image, then when I will send to update here's the error Call to a member function getClientOriginalName()
This is my Controller
public function updateBook(Request $request, $id){
$book = DB::table('books')->where('id',$id);
$old = $book->select('images');
$ChecK = 0;
$file = var_dump($request->file('images')->getClientOriginalName());
$filename = time().$file;
$path = public_path('/Uploads');
if($request->hasFile('images')){
$file = $request->file('images');
$file->move($path, $filename);
Storage::delete($old);
$ChecK = 1;
}
else {
dd('Request Hash No File!');
}
$data = [
'name'=> $request->input('bookName'),
'year'=> $request->input('tahunT'),
'author'=> $request->input('author'),
'summary'=> $request->input('Summary'),
'publisher'=> $request->input('publishers'),
'pageCount' => $request->input('pageCount'),
'readPage'=> $request->input('ReadPage'),
'finished' => '$pageCount' == '$readPage' ? true : false,
'reading' => '$readPage' > 0 ? true : false,
'updatedAt'=> new DateTime()
];
if( $ChecK == 1){
$data = ['images' => $filename];
$book->update($data);
return redirect('home')->with('status', 'update succesfully');
}
else {
$data = ['images' => $old];
$book->update($data);
return redirect('home')->with('status', 'Update with old image ');
}
}
Here is the view
<div class="card-body">
#if (session('status'))
<div class="alert alert-success" role="alert">
{{ session('status') }}
</div>
#endif
#foreach ($toEdit as $dt)
<form class="row g-3" enctype="multipart/form-data" method="POST" action="{{ route('update', $dt->id) }}" value="PUT">
{{ csrf_field() }}
<div class="col-md-6">
<label for="bookName" class="form-label">Nama Buku:</label>
<input type="text" class="form-control" name ="bookName"id="bookName" value="{{ ($dt->name) }}">
</div>
<div class="col-md-3">
<label for="tahunT" class="form-label">Tahun Terbit : </label>
<input type="number" class="form-control" name="tahunT" id="tahunT" value="{{ ($dt->year) }}">
</div>
<div class="col-md-3">
<label for="author" class="form-label">Author : </label>
<input type="text" class="form-control" name="author" id="author" value="{{ ($dt->author) }}">
</div>
<div class="col-md-6">
<label for="publishers" class="form-label">Publisher : </label>
<input type="text" class="form-control" name="publishers" id="publishers" value="{{ ($dt->publisher) }}">
</div>
<div class="col-md-3">
<label for="pageCount" class="form-label">Page Count :</label>
<input type="number" class="form-control" name="pageCount" id="pageCount" value="{{ ($dt->pageCount) }}">
</div>
<div class="col-md-3">
<label for="ReadPage" class="form-label">Read Page :</label>
<input type="number" class="form-control" name="ReadPage" id="ReadPage"value="{{ ($dt->readPage) }}">
</div>
<div class="col-12">
<label for="Summary" class="form-label">Summary :</label>
<textarea class="form-control" name="Summary" id="Summary">{{ ($dt->summary) }}</textarea>
</div>
<div class="col-md-12">
<label for="images" class="form-label">Book Image :</label>
<input type="file" class="form-group" name="images">
<br>
<img src="{{ asset('Uploads/'.$dt->images) }}" widht="300px"/>
<br>
</div>
<div class="col-12">
<button type="submit" class="btn btn-primary">Update</button>
</div>
</form>
#endforeach
</div>
Here, I will update the data, if user want to change the images, so the image will be update and if no, the images use the old one. It's rull same as the other input. But, when I try to upload the new one, the error Call to a member function getClientOriginalName() happen.
Do you have any suggestion to this? I already add the code enctype="multipart/form-data" and var_dump() but the error was same. Thank you :)
You have to check, with a condition, if your image is null or not in order to avoid this error.
Try something like :
if ( isset($request->file('images')) != null ) {
$ChecK = 0;
$file = $request->file('images')->getClientOriginalName();
$filename = time().$file;
$path = public_path('/Uploads');
}
//..
Just add a simple condition :
If($request->file('image')) {
...
$request->images->getClientOriginalNe();
.....
}

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.

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">

Hidden type input value not being passed in Laravel gallery Project

I have created an album. I am trying to upload photos to the album and storing the album_id through the 'hidden' type input. When i check the source code, album_id is shown in 'value' attribute but unfortunately the value is not being passed to the query during form submission.
My create method of PhotoController which shows the form
public function create($id)
{
$albums = Album::where('id',$id)->first();
return view('admin.pages.photos',compact('albums', 'id'));
}
Here is the form.
<div class="container">
<div class="row">
<a class="btn btn-success" href="/gallery/{{$albums->slug}}">Back to Gallery</a>
<h4>Upload Photos to <strong>{{$albums-> name}}</strong> Gallery</h4>
#if (session('status'))
<div class="alert alert-success">
{{ session('status') }}
</div>
#endif
<img class="thumbnail" src="/images/gallery/{{$albums->cover_pic}}" alt="{{$albums->name}}">
</div>
<div class="col-md-8">
<form class="form-horizontal" action="/photo" method="POST" enctype="multipart/form-data" >
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="form-group">
<label class="col-md-8">Photo Title:</label>
<input type="text" name="photo_name" class="form-control" placeholder="Name of the Photo" value="{{ old('photo_name') }}" >
</div>
<div class="form-group">
<label class="col-md-8">Description</label>
<input type="text" name="desc" class="form-control" placeholder="Write Description" value="{{ old('desc') }}">
</div>
<div class="form-group">
<label class="col-md-8">Upload Pic</label>
<input type="file" name="photo" class="form-control" value="{{old('photo')}}" >
</div>
<input type="hidden" name="album_id" value="{{$albums->id}}">
<button type="submit" name="submit" class="btn btn-success waves-effect waves-light m-r-10">Submit</button>
</form>
and the store method
public function store(Request $request)
{
$this->validate($request, [
'photo_name'=>'required|min:3',
'desc'=>'required',
'photo'=>'required'
]);
$photo = new Photo;
$photo->album_id = $request->album_id;
$photo->photo_name = $request->photo_name;
$str = strtolower($request->photo_name);
$photo->slug = preg_replace('/\s+/', '-', $str);
if($file=$request->file('photo')){
$name = time().'.'.$file->getClientOriginalName();
$file->move('images/gallery', $name);
$photo['photo'] = $name;
}
$photo->desc = $request->desc;
$photo->save();
return redirect()->back()->with('status', 'Photo Successfully Added!');
}

Laravel 5 session()->keep method not working

I have a view with an input date field and a table beneath that. The table is populated based on the date entered. When the date is entered I use a POST method on the form which handles the DB request and returns the same view with the data. I'd like to also return the original date that was entered. I tried session()->keep and flashOnly methods. None return the input date to the view.
My controller:
public function groupTestAthletes(Request $request)
{
$inputDate = null;
$tests = null;
if ($request['tgroupdate']){
$inputDate = Carbon::createFromFormat('d/m/Y', $request['tgroupdate']);
$tests = Test::where('test_date', '=', $inputDate->format('Y-m-d'))
->orderBy('athlete_id', 'desc')
->get();
}
$request->session()->keep(['tgroupdate']);
//$request->flashOnly(['tgroupdate']);
return view('npr.test_athletes', ['tests' => $tests]);
My view:
<form class="form-inline" role="form" method="POST" action="{{ route('admin.search_tgroup') }}">
{{ csrf_field() }}
<div class="form-group">
<label for="tgroupdate" class="control-label">Test Date</label>
<div class="input-group date" id="testgroupdatepicker">
<input name="tgroupdate" type="text" style="background-color:#ffffff" readonly=""
value="{{ Session::get('tgroupdate') }}" class="form-control">
<div class="input-group-addon">
<span class="glyphicon glyphicon-th"></span>
</div>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Search Athletes
</button>
<input type="hidden" name="_token" value="{{ Session::token()}}">
</div>
</form>
You dont need to save the date in session. You can save the date in a variable,send it to the view and in the view you can check if variable exist using isset php function.
In Controller
public function groupTestAthletes(Request $request)
{
$inputDate = null;
$tests = null;
if ($request['tgroupdate']){
$inputDate = Carbon::createFromFormat('d/m/Y', $request['tgroupdate']);
$tests = Test::where('test_date', '=', $inputDate->format('Y- m-d'))
->orderBy('athlete_id', 'desc')
->get();
}
return view('npr.test_athletes', ['tests' => $tests,'selected_date' => $request['tgroupdate']]);
And in the view,
<form class="form-inline" role="form" method="POST" action="{{ route('admin.search_tgroup') }}">
{{ csrf_field() }}
<div class="form-group">
<label for="tgroupdate" class="control-label">Test Date</label>
<div class="input-group date" id="testgroupdatepicker">
<input name="tgroupdate" type="text" style="background-color:#ffffff" readonly=""
value="#if(isset($selected_date)) $selected_date #endif" class="form-control">
<div class="input-group-addon">
<span class="glyphicon glyphicon-th"></span>
</div>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Search Athletes
</button>
<input type="hidden" name="_token" value="{{ Session::token()}}">
</div>
</form>
Edit: This minor change in the view gave the optimal solution.
value="#if(isset($selected_date)){{$selected_date}}#endif"

Resources