How can I overwrite my file images in laravel - php

I would like to ask how can i overwrite/update my images inside the form and store in database? I tried doing it but it is not working, i get the id correct but when i upload new image and text, it is not updating my old file. Below i attached my code.
company controller
public function update(Request $request, $id)
{
$this->validate($request, [
'company_logo' => 'required|image|max:2048',
'company' => 'required',
]);
// dd(123);
$company = Company::find($id)->first();
// dd($company);
// $company = Company::where(['companies.id' => $id])->first();
if($request->file != '')
{
$path = public_path().'/uploads/images/';
$file = $request->file;
$filename = $file->getClientOriginalName();
$file->move($path, $filename);
$company->update(['file' => $filename]);
return redirect()->route('company.index');
$company->file = $path.$filename;
}
$company->company = $request->company;
$company->save();
return redirect()->route('company.index');
}
public function insert_logo(Request $request)
{
$company = new Company();
$company->company = request('company');
$company->company_logo = request('company_logo|file|image|max:10,485,760');
// uploading image file to database
if
($file = $request->hasFile('company_logo')) {
$file = $request->file('company_logo');
$filename = time() . '.' .$file->getClientOriginalName();
$destinationPath = public_path('/uploads/images/');
$file->move($destinationPath, $filename);
$company->company_logo = $filename;
}
$company->save();
return back();
}
edit modal for company
<div class="modal" id="modal-edit">
<div class="modal__content">
<div class="intro-y flex items-center p-5">
<h2 class="text-lg font-medium mr-auto">
Edit Company
</h2>
</div>
<form action="{{ route('company.update', $company->id) }}" method="post">
#csrf
#method('PUT')
<div class="intro-y box p-5">
<div>
<label>Company Logo</label>
<div class="mt-2">
<div class="mt-2">
<div class="row mt-4">
<div class="col-md-8">
<input type="file" name="company_logo"/>
</div>
</div>
</div>
</div>
<div class="mt-3">
<input type="text" placeholder="Company Name" name="company"
class="input w-full border col-span-4 form-control tail-select" value="{{ $company->company}}">
</div>
<div class="text-right mt-5">
<button type="button" data-dismiss="modal"
class="button w-24 border text-gray-700 dark:border-dark-5 dark:text-gray-300 mr-1">Cancel</button>
<button type="submit" class="button w-24 bg-theme-1 text-white">Update</button>
</div>
</div>
</div>
</div>
</form>
</div>
<script type="text/javascript">
$('#modal-edit').modal('show')</script>
I might be wrong inside the function but I am not sure where it went wrong. so far only the company name is showing, but still even if I change my company name, and click button update, it wont overwrite my old one

Form Tag missed enctype="multipart/form-data"
<form enctype="multipart/form-data" action="{{ route('company.update', $company->id) }}" method="post">
once you called find then no need first so remove ->first()
$company = Company::find($id);
It should be $request->company_logo not $request->file
$company = Company::find($id);
if($request->hasFile('company_logo'))
{
$path = public_path().'/uploads/images/';
$file = $request->company_logo;
$filename = $file->getClientOriginalName();
$file->move($path, $filename);
$company->company_logo =$path.$filename;
}
$company->company = $request->company;
$company->save();
return redirect()->route('company.index');
Usually full path is not saved in db.Better only save filename so that you can keep base path in filesystem configuration.

Related

Laravel image upload to database

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/

Laravel inserting normal image, value become null

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

Photo Gallery: Adding Photos

Ok so I’m working on a photo gallery project and I’m trying to add a photo. I have a page that allows the user to browse for a picture and another input field for adding a title for their picture. The added picture path and title should be added to a xml file where the images are being pulled from.
Also if it helps, I'm using Materialize css. I’m not sure why it’s not working but this is what I currently have:
Form
<form action="../models/addPicture.php" method="POST" enctype="multipart/form-data">
<div class="row center">
<h5>Choose a Photo to Upload</h5>
</div>
<div class="file-field input-field">
<div class="btn-large black">
<span>Browse</span>
<input type="file" />
</div>
<div class="file-path-wrapper">
<input class="file-path validate" type="text" placeholder="Upload file" name="picFile" />
</div>
</div>
<div class="row">
<div class="input-field">
<input type="text" name="picTitle" class="validate" placeholder="Enter a title for your picture.">
</div>
</div>
<div class="row center">
<button class="btn-large black" type="submit">Add Pic!</button>
</div>
Method:
<?php
if (($_FILES['picFile']['name']!="")){
$target_dir = "../images/";
$file = $_FILES['picFile']['name'];
$path = pathinfo($file);
$filename = $path['basename'];
$ext = $path['extension'];
$temp_name = $_FILES['picFile']['temp_name'];
$path_filename_ext = $target_dir.$filename.".".$ext;
if (file_exists($path_filename_ext))
{
$message = "Added Picture Failed please try again.";
$color = "red-text";
header("Location: ../index.php?Message=".$message."&color=".$color);
}
else
{
move_uploaded_file($temp_name,$path_filename_ext);
$message = "Added Picture Successfully. Please Click Reset to View.";
$color = "green-text";
header("Location: ../index.php?Message=".$message."&color=".$color);
}
}
else
{
$message = "Please enter a picture to submit.";
$color = "red-text";
header("Location: ../index.php?Message=".$message."&color=".$color);
}
?>
I have found a small mistake in your code at line no. 9.
$temp_name = $_FILES['picFile']['temp_name'];
Change the ['temp_name]; to ['tmp_name];
Use this code.
$temp_name = $_FILES['picFile']['tmp_name'];

I have 4 rows and 4 columns each row display images from different tables how to update any images in laravel framework

update function of laravel framework
public function update(Request $request, $id)
{
if(isset($_POST['commer']))
{
$commercial = BestCommercialPhoto::findOrFail($id);
$input = $request->all();`enter code here`
if($file = $request->file('file'))
{
$name = time().$file->getClientOriginalName();
$file->move('images',$name);
$input['file'] = $name;
}
$commercial->update($input);
}
elseif(isset($_POST['fash']))
{
$fashion = BestFashionPhoto::findOrFail($id);
if($file = $request->file('file')){
$name = time().$file->getClientOriginalName();
$file->move('images',$name);
$input['file'] = $name;
}
$fashion->update($input);
}
elseif(isset($_POST['wed']))
{
$wedding = BestWeddingPhoto::findOrFail($id);
if($file = $request->file('file')) {
$name = time().$file->getClientOriginalName();
$file->move('images',$name);
$input['file'] = $name;
}
$wedding->update($input);
}
elseif(isset($_POST['make']))
{
$making = BestMakingPhoto::findOrFail($id);
if($file = $request->file('file'))
{
$name = time().$file->getClientOriginalName();
$file->move('images',$name);
$input['file'] = $name;
}
$making->update($input);
}
else
{
return "Not Working Properly";
}
}
This is code for edit
public function edit($id)
{
$commercial = BestCommercialPhoto::findOrFail($id);
return view('admin.bestPhoto.edit_comm',compact('commercial'));
}
Below is HTML code for edit page. I am not able to update if I click on 2nd row which contains[enter image description here][1] 4 fashion category image. If I click to update Fashion category image its displays the 1st-row image how to update the images of different rows
<form method="post" action="/admin/bestPhoto/{{$commercial->id}}" enctype="multipart/form-data">
<input type="hidden" name="_method" value="PATCH">
{{ csrf_field()}}
<div class="card shadow-lg">
<div class="card-body">
<div class="form-group">
<div class="text-center">
<img class="img-fluid" src="/images/{{$commercial->file}}">
</div>
</div>
<div class="form-group">
<div class="text-center">
<input type="file" name="file" required>
</div>
</div>
<div class="form-group" style="width:25%">
<div class="text-center" >
<button name="commer" class="btn btn-outline-primary" type="submit"
style="width: 50%;">Save
</button>
</div>
</div>
</div>
</div>
</form>

Uploading Images in laravel using Intervention

i am tring to upload images in laravel 5.6 using intervention and its working perfectly, the only problem is the path it is storing on the database is like /var/www/Laravel/project/public/uploads/students/1534413021.jpg and what i want is for it to store it as /uploads/students/1534413021.jpg.
Here is my form
<form class="form-horizontal" method="post" action="{{ route('student.Avatar.submit',$student->id)}}" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="form-group ">
<label class="col-sm-2 control-label">Select Image To Upload:</label>
<div class="col-sm-10 {{ $errors->has('avatar') ? ' has-error' : '' }}">
<input type="file" name="avatar" value="{{ old('avatar') }}" class="form-control rounded">
#if ($errors->has('avatar'))
<span class="help-block">
<strong>{{ $errors->first('avatar') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group">
<div class="col-sm-4 col-sm-offset-2">
<button type="submit" class="btn btn-primary btn-rounded btn-block">Save changes</button>
</div>
</div>
</form>
and here is the controller
public function uploadAvatar(Request $request, Student $student)
{
$validatedData = $request->validate([
'avatar' => 'required | mimes:jpeg,jpg,png,bmb,gif,svg',
]);
if ($request->hasFile('avatar')) {
$image = $request->file('avatar');
$fileName = time() . '.' . $image->getClientOriginalExtension();
$location = public_path('uploads/students/'.$fileName);
Image::make($image)->resize(800,400)->save($location);
$studentUpdate = Student::where('id',$student->id)
->update([
'avatar'=>$location,
]);
if ($studentUpdate) {
return redirect()->route('students.profile',$student->id)->with('success','Student Profile Created Successfully');
}else{
return back()->withInput()->with('errors','Error adding new parent.');
}
}
return back()->withInput()->with('errors','PLease Select An Image.');
}
change your path while saving like this:
$location = public_path('uploads/students/'.$fileName);
To this:
$location = 'uploads/students/'.$fileName;
It will automatically go to public/$location and save the file and you will have only required string in database;
You should try this:
public function uploadAvatar(Request $request, Student $student)
{
$validatedData = $request->validate([
'avatar' => 'required | mimes:jpeg,jpg,png,bmb,gif,svg',
]);
if ($request->hasFile('avatar')) {
$image = $request->file('avatar');
$fileName = time() . '.' . $image->getClientOriginalExtension();
$location = public_path('uploads/students/');
$uploadImage = Image::make($image->getRealPath())->resize(800,400);
$uploadImage->save($location.'/'.$fileName);
$imageName = public_path('uploads/students/'.$fileName);
$studentUpdate = Student::where('id',$student->id)
->update([
'avatar'=>$imageName,
]);
if ($studentUpdate) {
return redirect()->route('students.profile',$student->id)->with('success','Student Profile Created Successfully');
}else{
return back()->withInput()->with('errors','Error adding new parent.');
}
}
return back()->withInput()->with('errors','PLease Select An Image.');
}

Categories