I want to update an image in laravel 5.6.
In my app, the image is uploading and inserting into the database correctly but when I want to update the image it cannot update the old image.
How can I update the image with other field?
This is my view:
<form method="post" action="{{ route('employee.update', $employee->id) }}" enctype="multipart/form-data">
#csrf
#method("PATCH")
<input type="hidden" name="profile_old_image" value="{{$employee->profile_pic}}">
<div>
<input type="file" name="profile_pic" class="form-contrle" >
</div>
<div>
<input placeholder='Your Name' type='text' name='name' value="{{$employee->name}}" class="form-control">
</div>
</form>
This is my controller:
public function update(Request $request, $id)
{
$rules = [
'name' => 'required',
'father_name' => 'required',
'phone_no' => 'required',
'cnic' => 'required'
];
$validate = $this->validate($request, $rules);
$file = $request->file('profile_pic');
if($file == '')
{
$profile_pic = $request->profile_old_image;
}
else
{
$file = $request->file('profile_pic');
$fileName = time().'.'.$file->getClientOriginalExtension();
$destinationPath = public_path('/admin/images/employees');
$file->move($destinationPath,$fileName);
$profile_pic = '/admin/images/employees/'.$fileName;
}
//dd($request->all());
$employee = Employee::find($id);
$employee->name = $request->name;
$employee->father_name = $request->father_name;
$employee->phone_no = $request->phone_no;
$employee->cnic = $request->cnic;
$employee->desg_id = $request->desg_id;
$employee->profile_pic = $profile_pic;
$employee->save();
return redirect('admin/employee')->with('message', 'Records Successfully Updated');
}
Related
i have this code in my controller that can make me upload successfully just one file , and i want to upload many files in once time :
public function store(Request $request, $id) {
$request->validate([
'image' => 'required',
]);
$listing = Listing::findOrFail($id);
$image = new Listingimage();
if ($request->hasFile('image')) {
$file = $request->file('image');
$extention = $file->getClientOriginalExtension();
$filename = time() . '.' . $extention;
$file->move('assets/images/listingimages/', $filename);
$fileOriginalName = $file->getClientOriginalName();
}
$image->listing_id = $id;
$image->image_url = $filename;
$image->nom_image = $fileOriginalName;
$image->save();
return redirect()->back();
}
i use also this input :
<form action="{{ route('Listingimages.store', $listing->id) }}" method="POST" enctype="multipart/form-data">
<input type="hidden" name="_method" value="PUT" />
{{csrf_field()}}
{{method_field('PUT')}}
<label> Insert image</label>
<input type="file" name="image" id="files" class="form-control" multiple>
so , how can i upload many files in once time ?
change input name
<input type="file" name="image[]" id="files" class="form-control">
controller
public function store(Request $request, $id) {
$request->validate([
'image' => 'required',
]);
$listing = Listing::findOrFail($id);
if ($request->hasFile('image')) {
foreach($request->file('image') as $file)
{
$image = new Listingimage();
$file = $request->file('image');
$extention = $file->getClientOriginalExtension();
$filename = time() . '.' . $extention;
$file->move('assets/images/listingimages/', $filename);
$fileOriginalName = $file->getClientOriginalName();
$image->listing_id = $id;
$image->image_url = $filename;
$image->nom_image = $fileOriginalName;
$image->save();
}
}
return redirect()->back();
}
This function is the function I use to store a new company:
public function store(Request $request)
{
$file = $request->file('logo');
$filename = 'company-logo-' . time() . '.' . $file->getClientOriginalExtension();
$path = $file->storeAs('public', $filename);
dd($path);
Company::create([
'name' => $request->name,
'email' => $request->email,
'logo' => $request->logo,
'website' => $request->website
]);
return redirect('/company/all');
}
This view is the one with the form:
#extends('layouts.app')
#section('content')
<div class="card">
<div class="card-body">
<h4 class="card-title">Create a Company</h4>
</div>
<div class="container">
<div class="jumbotron">
<ul class="list-group">
<li class="list-group-item">
<h3>Enter Company Information:</h3>
<form action="{{ route('company.store') }}" enctype="mutlipart/form-data" method="POST">
#csrf
<div class="form-group">
<input type="text" class="form-control" name="name" placeholder="Company name" value="{{ old('name') }}">
</div>
<div class="form-group">
<input type="text" class="form-control" name="email" placeholder="Email" value="{{ old('email') }}">
</div>
<div class="form-group">
<input class="form-control" type="file" name="logo">
</div>
<div class="form-group">
<input class="form-control" type="url" name="website" placeholder="Website" value="{{ old('website') }}">
</div>
<button class="btn btn-primary" type="submit">Add Company</button>
</form>
</li>
</ul>
</div>
</div>
</div>
#endsection
This is the route:
Route::post('/add', 'CompaniesController#store')->name('store');
Well, what happens when I try to submit this form is that $file variable always returned with null:
Error
Call to a member function getClientOriginalExtension() on null
http://localhost:8000/company/add
Basically what I want to do is send the name of the image to the database and upload the image to my public folder. Neither happens with this code. when I erase the part starting from $file till dd($path); it adds the values to the database but the image hasn't been uploaded.
Any help? Thanks in advance.
First of all the attribute on the form is wrong which is enctype="mutlipart/form-data" and it should be enctype="multipart/form-data"
or an alternative you can use below code according to your requirements:
if($request->hasFile('logo')){
$file = $request->file('logo');
$fileName = 'company-logo-' .time().$file->getClientOriginalName();
Storage::put('public/'.$fileName,file_get_contents($file));
now you can store the $filename variable in database and image will be uploaded to storage/app/public folder
}
please add use Storage on top of file and run php artisan storage:link to make symbolic link between storage folder and public folder
First you change enctype="multipart/form-data" instead of enctype="mutlipart/form-data" in your form.
Then put this code to your controller
public function store(Request $request)
{
if($request->hasFile('logo')) {
$img_ext = $request->file('logo')->getClientOriginalExtension();
$filename = 'company-logo-' . time() . '.' . $img_ext;
$path = $request->file('logo')->move(public_path(), $filename);//image save public folder
}
//You should store only filename not path in db
Company::create([
'name' => $request->name,
'email' => $request->email,
'logo' => $filename,
'website' => $request->website
]);
return redirect('/company/all');
}
try changing to:
public function store(Request $request)
{
$file = $request->file('logo');
$path = '';
if($file) {
$filename = 'company-logo-' . time() . '.' . $file->getClientOriginalExtension();
$path = $file->storeAs('public', $filename);
}
Company::create([
'name' => $request->name,
'email' => $request->email,
'logo' => $path,
'website' => $request->website
]);
return redirect('/company/all');
}
if (Input::hasFile('logo')) {
$file = Input::file('logo');
$ext = $file->getClientOriginalExtension();
$file_name = 'company-logo-' . time() . ".{$ext}";
$path = base_path().'/public/';
$file->move($path , $file_name);
}
You can use the file pond. The core library is written in vanilla JavaScript and therefore can be used everywhere. Visit: https://pqina.nl/filepond/
I am Learning at the moment. But got one problem. I have build a database:
and my controller code is:
UploadController.php
public function upload(Request $request, Task $task)
{
$task->image = Request::get('image');
$task->save();
return redirect('/');
}
TaskController.php
public function update(Request $request, Task $task)
{
if(isset($_POST['delete'])) {
$task->delete();
return redirect('/');
}
else
{
$task->description = Request::get('description');
$task->save();
return redirect('/');
}
}
public function upload(Request $request, Task $task)
{
if(isset($_POST['delete'])) {
$task->delete();
return redirect('/');
}
else
{
$task->image = Request::get('image');
$task->save();
return redirect('/');
}
}
edit.blade.php
<div class="container">
<h1>Edit the Task</h1>
<form method="POST" action="/task/{{ $task->id }}">
<div class="form-group">
<textarea name="description" class="form-control">{{$task->description }}</textarea>
</div>
<form action="{{ URL::to('upload') }}" method="post" enctype="multipart/form-data">
<label>Select image to upload:</label>
<input class="btn btn-primary" type="file" name="file" id="file">
<input class="btn btn-primary" type="submit" value="Insert" name="insert" enctype="multipart/form-data">
<input class="btn btn-primary" type="hidden" value="{{ csrf_token() }}" name="_token">
<img class="user_avatar" src="{{url('public/uploads/test.jpg')}}">
</form>
<div class="form-group">
<button type="submit" name="update" class="btn btn-primary">Update task</button>
</div>
<div class="form-group">
<button type="submit" name="update" class="btn btn-primary">Update task</button>
</div>
These are my code, when I try to insert an image in to my database, it become null and self create another set of null data. How can I fix this problem? Thank you.
This is my database at the moment
This is the inside value of the image
Try this
public function upload(Request $request, Task $task)
{
if(isset($_POST['delete'])) {
$task->delete();
return redirect('/');
}
else
{
$task->image = \Storage::disk('public')->put('image', $request->file('image'));
$task->save();
return redirect('/');
}
}
and
filesystems.php
inside
'public' => [
'driver' => 'local',
'root' => public_path() . '/uploads',
'url' => env('APP_URL').'/uploads',
'visibility' => 'public',
],
inside blade
<input class="btn btn-primary" type="file" name="image" id="file">
change name="image" then only you can get $request->file('image')
Use this to same image directly to db in BLOB field
$task->image = request('image')->encode('jpg', 80);
$task->save();
You can update the variables as suitable to you but the solution is in encode
You can encode your image first like this
$b64 = base64_encode(request('image'));
you can not save image in database, you must move image to a folder and save address it in database and type column image must be varchar text.
change code to :
public function storeTask()
{
$task = new Task();
$task->name = request('name');
$task->description = request('description');
$image = request->file('image');
$extention = $image->getClientOriginalExtension();
$name = rand(1000, 9999) '.' . $extention;
$path = public_path() . '/images/' . $name;
$image->move($path);
$task->image = $path;
$task->save();
return redirect('/task');
}
Try the following code:
$path = $request->file('image')->getRealPath();
$image = file_get_contents($path);
$base64 = base64_encode($image);
$task->image = $base64;
$task->save();
I have a Tag.php model which has hasMany relationship with the Image.php model. I already have a working images and tags tables, however, I am not sure how to make the image_tag table be automatically filled when I upload an image with a certain tag. If I were using vanilla PHP, I would insert the image first, then get its id, get the id of the tag and then make a second insert into the image_tag table. This is my code:
Upload view:
#extends('layouts.app')
#section('content')
<div class="wrapper">
<div class="main">
<div class="formContainer">
<form action="{{ route('imageUpload') }}" method="POST" enctype="multipart/form-data">
<label for="name">Name</label>
<input class='contactInput' type="text" name="name" placeholder="Image Name">
<label for="description">Description</label>
<input class='contactInput' type="text" name="description" placeholder="Description">
<label for="description">Tag</label>
<select class='tagSelect' name='tags'>
#foreach($tags as $tag)
<option value='{{$tag->name}}'>{{$tag->name}}</option>
#endforeach
</select>
<input type="file" name="image">
{{ csrf_field() }}
<button class='contactSubmit' type="submit" name="submit">UPLOAD</button>
</form>
</div>
</div>
</div>
#endsection
uploadImage function from my ImagesController:
class ImagesController extends Controller
{
public function uploadImage(Request $request){
$this->validate($request, [
'name' => 'required|max:120',
'description' => 'max:120|nullable',
'image' => 'required|max:1999'
]);
$name = $request['name'];
$description = $request['description'];
$tag = $request['tags'];
$userId = auth()->user()->id;
$file = $request->file('image')->getClientOriginalName();
$fileName = pathinfo($file, PATHINFO_FILENAME);
$extension = $request->file('image')->getClientOriginalExtension();
$fileNameToStore = $fileName.'_'.time().'.'.$extension;
$fileNameToStore = str_replace(' ', '', $fileNameToStore);
$path = $request->file('image')->storeAs('public/images/uploaded', $fileNameToStore);
$image = new Image();
$image->name = $name;
$image->description = $description;
$image->user_id = $userId;
$image->file_name = $fileNameToStore;
$image->save();
return redirect()->route('home');
}
Well you are going all wrong.
your relation is Many to Many
so in your Tag model you should do
public function images()
{
return $this->belongsToMany(Image::class, 'your pivot table name in this case image_tag ','tag_id','image_id');
}
and in Image model
public function tags()
{
return $this->belongsToMany(Tag::class, 'your pivot table name in this case image_tag ','image_id','tag_id');
}
then you can save an image and attach tags like this
$image->tags()->attach($tags)
which $tags is an array of ids like [1,2,3,4,5,6]
$image = new Image();
$image->name = $name;
$image->description = $description;
$image->user_id = $userId;
$image->file_name = $fileNameToStore;
$image->save();
$image->tags()->attach($tags);
hope it helps
I am trying to upload multiple images in a single row in a database table and access them in a show page.I have tried this tutorial:
laraveldaily.com/upload-multiple-files-laravel-5-4/
but there two different tables are made and a relation is established.
I want this to happen in a single table.
here is what worked best for me:
first do this in your form:
<form class="form-horizontal" enctype="multipart/form-data" method="post" action="/details">
and this for multiple selection:
<input required type="file" class="form-control" name="images[]" placeholder="address" multiple>
Now do this in your controller:
public function store(request $request) {
$input=$request->all();
$images=array();
if($files=$request->file('images')){
foreach($files as $file){
$name=$file->getClientOriginalName();
$file->move('image',$name);
$images[]=$name;
}
}
/*Insert your data*/
Detail::insert( [
'images'=> implode("|",$images),
'description' =>$input['description'],
//you can put other insertion here
]);
return redirect('redirecting page');
}
Hope this works
<form role="form" method="post" action="{{URL::to('addimage')}}" enctype="multipart/form-data">
<div class="form-group" style="padding-bottom: 15px">
<label class="col-lg-3">Upload</label>
<input class="btn btn-primary" type="file" name="files[]" > <br/>
</div>
</form>
$images = $request->file('files');
if ($request->hasFile('files')) :
foreach ($images as $item):
$var = date_create();
$time = date_format($var, 'YmdHis');
$imageName = $time . '-' . $item->getClientOriginalName();
$item->move(base_path() . '/uploads/file/', $imageName);
$arr[] = $imageName;
endforeach;
$image = implode(",", $arr);
else:
$image = '';
endif;
DB::table('fooo')->insert(
array(
'image' => $image
)
);
Session::flash('message', 'Image upload successfully successfully');
return redirect('/addimage');
this can also be achieved with
foreach ($request->file('files') as $index => $item) {
$path = $request->files[$index]->store('images');
}
html
<input type="file" name="images[]" multiple>
controller : store folder storage
foreach ($request->file('images') as $imagefile) {
return $imagefile->store('images','public');
}
This one works for me.
Form:
<form class="form-horizontal" enctype="multipart/form-data" method="post" action="/details">
and this for multiple selection image:
<input required type="file" class="form-control" name="image[]" placeholder="address" multiple>
Now do this in Our Model:
protected fillable = ['producd','image', ];
Now do this in Our controller:
public function store(Request $request)
{
$image = array();
if($file = $request->file('image')){
foreach($file as $file){
$image_name = md5(rand(1000,10000));
$ext = strtolower($file->getClientOriginalExtension());
$image_full_name = $image_name.'.'.$ext;
$uploade_path = 'uploads/images/';
$image_url = $uploade_path.$image_full_name;
$file->move($uploade_path,$image_full_name);
$image[] = $image_url;
}
Image::insert([
'image' => implode('|', $image),
'producd' => $request->producd,
]);
return redirect('/image.index'));
}
}
$images = array();
if ($request->hasFile('gallery_image')) {
$files = $request->file('gallery_image');
foreach ($files as $file) {
$image_name = md5(rand(1000, 10000));
$ext = strtolower($file->getClientOriginalExtension());
$image_full_name = $image_name . '.' . $ext;
$file->move('Your image path here',
$image_full_name);
$images[] = $image_full_name;
}
}
$house->gallery_image = json_encode($images);