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();
Related
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.
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.');
}
How i upload multiple image's and get it in view with laravel 5.3 ?
My Controller function is:
public function newOffer(Request $request){
$validate_marge['img'] = 'required|image|mimes:png,jpg,jpeg';
$validator = Validator::make($request->all(), $validate_marge);
if ($validator->fails()){
return back()->withInput()->withErrors($validator);
}else{
$post = new Post();
if (Input::hasFile('img')){
$file = Input::file('img');
$file->move(public_path('img/offers').'/', $file->getClientOriginalName());
$post->img = $file->getClientOriginalName();
}
}
$post->title = Input::get('title');
$post->category_id = Input::get('category_id');
$post->second_title = Input::get('second_title');
$post->description = Input::get('description');
$post->location = Input::get('location');
$post->price = Input::get('price');
$post->save();
return back();
}
and is HTML form is:
<form class="form-horizontal" method="post" action="{{ url('newOffer') }}"
enctype="multipart/form-data">
{{ csrf_field() }} <div class="form-group">
<label class="col-md-4 control-label">Select IMG's</label>
<div class="col-md-6">
<input type="file" class="form-control" id="image"
name="images[]"
required
data-validation-required-message="Please choose image" multiple>
<p class="help-block">{{$errors->first('images')}}</p>
</div>
</div> <input type="submit" value="Add" class="btn btn-primary" style="width: 100%"></form>
what i do in Controller to do it and how i preview in post??
Thank You all
Change
if (Input::hasFile('img')){
$file = Input::file('img');
$file->move(public_path('img/offers').'/', $file->getClientOriginalName());
$post->img = $file->getClientOriginalName();
}
to
if (Input::hasFile('img')){
$files = Input::file('img');
foreach ($files as $file){
$file->move(public_path('img/offers').'/', $file->getClientOriginalName());
}
$post->img = $file->getClientOriginalName();
$post->title = Input::get('title');
$post->category_id = Input::get('category_id');
$post->second_title = Input::get('second_title');
$post->description = Input::get('description');
$post->location = Input::get('location');
$post->price = Input::get('price');
$post->save();
}
return back();
you just need to loop through your uploaded files
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));
}
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');
}