Laravel Call to undefined method Intervention\Image\File::delete() - php

I made a method which allows the user to update their profile picture. I also added a function which deletes their old profile picture if they update to a new one. But i get an error saying Call to undefined method Intervention\Image\File::delete().
What is causing this? In the code below it makes perfect sense for me. I hope you guys can help. Thanks in advance
Code:
UserController.php
public function update_avatar(Request $request) {
$this->middleware('auth');
if ($request->hasFile('avatar')) {
$avatar = $request->file('avatar');
$filename = Auth::user()->username . time() . '.' . $avatar->getClientOriginalExtension();
Image::make($avatar)->fit(300,300)->save( public_path('/uploads/avatars/' . $filename));
$user = Auth::user();
$user->avatar = $filename;
$user->save();
//Verwijderd vorige foto
if ($user->avatar != 'default.jpg') {
$path = 'uploads/avatars/';
$lastpath = Auth::user()->Avatarpath;
File::delete(public_path($path . $lastpath));
}
}
return view('user.profile', array('user' => Auth::user()));
Route: Route::post('{username}/profile', 'UserController#update_avatar');
The form that is supposed to do this.
<div class="row">
<div class="col l12 m12 s12">
<div class="card">
<div class="card-content">
<form enctype="multipart/form-data" action="profile" method="POST">
<input type="file" name="avatar">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="submit" class="pull-right btn btn-primary" value="Change profile">
</form>
</div>
</div>
</div>
</div>
Changing the picture works just fine. If I reload the page the profile picture is updated but it doesn't delete the old one.

try this. does this help.
public function update_avatar(Request $request) {
$this->middleware('auth');
if ($request->hasFile('avatar')) {
$avatar = $request->file('avatar');
$filename = Auth::user()->username . time() . '.' . $avatar->getClientOriginalExtension();
Image::make($avatar)->fit(300,300)->save( public_path('/uploads/avatars/' . $filename));
$user = Auth::user();
$user->avatar = $filename;
$user->save();
//Verwijderd vorige foto
if ($user->avatar != 'default.jpg') {
$path = public_path('uploads'.DIRECTORY_SEPARATOR.'avatars'. DIRECTORY_SEPARATOR.Auth::user()->Avatarpath);
if (file_exists($path)) {
unlink($path);
}
}
}
return view('user.profile', array('user' => $user));
}

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

Upload an image and file to forum

I have searched for the SO and didn't find any article or post related to this.
How do I upload an Image using the Image Intervention and upload a normal file with in a single forum without opening a new page for the uploads.
Hope the below Answer would help someone out there.
Blade
<form action="{{route('index.store')}}" enctype="multipart/form-data" method="POST">
<div class="form-group">
<label for="resume_path">Resume</label>
<input type="file" class="form-control"
name="resume_path">
</div>
<div class="form-group">
<label for="engineer_avatar">Profile Image</label>
<input type="file" class="form-control"
name="engineer_avatar">
</div>
</form>
Controller
use Image;
use App\Engineers;
*/
public function update(Request $request, $id)
{
$this->validate($request,[
'engineer_avatar' => 'image|mimes:jpeg,png,jpg|max:2048',
'resume_path' => 'file|mimes:doc,docx,pdf|max:2048',
// dimensions:min_width=600,min_height=400'
]);
$engineers = Engineers::findOrFail($id);
if($request->hasFile('engineer_avatar')){
$image = $request->file('engineer_avatar');
$filename = time() . '.' . $image->getClientOriginalExtension();
$location = public_path('images/engineer_avatar/' . $filename);
Image::make($image)->resize(600,400)->save($location);
$engineers->avatar_path = $filename;
}
if($request->hasFile('resume_path')){
$file = $request->file('resume_path');
$file_name1 = time() . '.' . $file->getClientOriginalExtension();
$file_path = public_path('resume/engineer/');
$engineers->resume_path = $file_name1;
$file->move($file_path, $file_name1);
$engineers->save();
}
To delete the file ::
public function destroy($id)
{
$engineers = Engineers::findOrFail($id);
unlink(public_path('images/engineer_avatar/' . $engineers->avatar_path ));
unlink(public_path('resume/engineer/' . $engineers->resume_path ));
$engineers->delete();
}

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.');
}

Unable to change Profile Picture Laravel

I am able to store the image in desired location but I am unable to view it.
When the page is reloaded ,the same default image appears .
Default image never changes to my desired Image.
My Controller File(UserController.php):
public function update_avatar(Request $request)
{
if($request->hasFile('avatar'))
{
$avatar = $request->file('avatar');
$filename = time(). '.' . $avatar->getClientOriginalExtension();
Image::make($avatar)->save(public_path('/src/uploads/avatars/' . $filename));
}
return redirect()->route('dashboard');
}
}
My Route file:
Route::post('/dashboard',[
'uses'=>'UserController#update_avatar',
]);
My view File:
<form action="/dashboard" method="post" enctype="multipart/form-data">
<div id="mySidenav" class="sidenav">
×
<input type="file" name="avatar" class="btn btn-sm btn-primary col-md-5" >
<input type="submit" class="pull-right btn btn-sm btn-primary " value="submit">
<input type="hidden" value="{{Session::token() }}" name="_token">
Remove
</div>
<div id="main">
<span style="font-size:30px;cursor:pointer" onclick="openNav()"><img src="download.jpg" class="img-circle img-responsive" alt="Placeholder image"></span>
</div>
</form>
Are you not saving the uploaded Image to the Database? Are you only uploading images to the dedicated Images Folder but not saving it to the Database? If you want, you can do this in your controller:
<?php
public function update_avatar(Request $request){
$avatarURI = null;
if($request->hasFile('avatar')) {
$avatar = $request->file('avatar');
$filename = time(). '.' . $avatar->getClientOriginalExtension();
Image::make($avatar)->save(public_path('/src/uploads/avatars/' . $filename));
$avatarURI = "src/uploads/{$filename}";
User::update();
}
// YOU MAY NEED TO PERSIST THIS IN THE DATABASE
// TO UPDATE THE avatar:
$usr = new \App\User();
$usr->update(['avatar' => $avatarURI, 'id'=>$userID]); //<== ID OF THE USER TO BE UPDATED...
return redirect()->route('dashboard', ['imgURI'=>$avatarURI, 'user'=>$usr]);
}
Change user with avatar attribute suit your need
public function update_avatar(Request $request)
{
if($request->hasFile('avatar'))
{
$avatar = $request->file('avatar');
$path = '/src/uploads/avatars/';
$filename = time(). '.' . $avatar->getClientOriginalExtension();
Image::make($avatar)->save(public_path($path . $filename));
$request->user()->avatar = $filename;
$request->user()->save();
}
return redirect()->route('dashboard');
}

Categories