I have edit form which is populated from database when I go to update page. Everything works fine except the image part. If I don't submit new image it deletes old one too.
This is my controller
public function update( ItemRequest $request){
$item = Item::find( $request['id'] );
$filename=null;
$image = $request->file('image');
if($request->hasFile('image'))
{
if($image->isValid()){
$extension = $image->getClientOriginalExtension();
$uploadPath = public_path(). '/uploads';
$filename = rand(111,999). '.'. $extension;
$image->move($uploadPath, $filename);
}
}
$item->title = $request['title'];
$item->category_id = $request['category_id'];
$item->price = $request['price'];
$item->description = $request['description'];
$item->image = $filename? $filename: $item->image;
$item->image = $filename;
if($item->save()){
if(!is_null($filename)){
$item_image = new Item_Images;
$item_image->image = $filename;
$item_image->item_id = $item->id;
$item_image->published = 1;
$item_image->save();
}
$request->session()->flash('alert-success','Item updated successfully.');
} else
$request->session()->flash('alert-error','Can not update item now. Plese tyr again!!.');
return redirect()->route('products');
}
And the corresponded fields for image on the form
#if( $item['image'] )
<div class="form-group">
{!! Form::label('inputImage', 'Existing Image', array('class'=> 'col-sm-2 control-label')) !!}
<div class="col-sm-10">
<img src="{!!asset('/uploads/'. $item['image'] )!!}" />
</div>
</div>
#endif
<div class="form-group">
{!! Form::label('inputImage', 'Image', array('class'=> 'col-sm-2 control-label')) !!}
<div class="col-sm-10">
{!! Form::file('image', ['class'=>'form-control', 'id'=>'inputImage']) !!}
</div>
</div>
First I check if there is image in database and if there is it is shown on the page. There there is the file field.
So is it possible to load as a value the current image in file field of form? Or this must be done in controller logic somehow?
Remove this line to fix the problem:
$item->image = $filename;
By doing this, you'll set image as null if no image was uploaded.
Related
So i was making a form that consists of three field, the title, thumbnail, and textarea(with texteditor) and it seems that it upload the image just fine since i notice that there is images that i had uploaded in my /public/image folder after i submit the form, but when i check the database the thumbnail field showed not the name of the file in the /public/image folder like 20190713125534.jpg but
C:\xampp\tmp\phpC18A.tmp
im confused i thought it doesn't upload the image at all, but as i explained earlier it does, so my question is how do i change the value of thumbnail field with the filename and how do i show the image in my view ?
this is my Blogcontroller.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Blog;
use Validator,Redirect,Response,File;
class BlogController extends Controller
{
public function index()
{
$blogs = Blog::get();
return view('post.post_textarea',[
'blogs' => $blogs
]);
}
public function store(Request $request)
{
Blog::create([
'name' => $request->name,
'message' => $request->message,
'thumbnail' => $request->thumbnail,
]);
if ($files = $request->file('thumbnail')) {
$destinationPath = 'public/image/'; // upload path
$profileImage = date('YmdHis') . "." . $files->getClientOriginalExtension();
$files->move($destinationPath, $profileImage);
$insert['thumbnail'] = "$profileImage";
}
return redirect()->back();
}
public function getFullPost($blog_id) {
$blogs = Blog::where('id', '=', $blog_id)->get();
return view('post.read')->with(compact('blogs'));
}
}
this is my view for the form
<form enctype="multipart/form-data" method="POST">
{{csrf_field()}}
<div class="form-group">
<h4 style="color: black;" >Judul</h4>
<br>
<input type="text" class="form-control" name="name">
</div>
<div class="form-group">
<h4 style="color: black;" >Thumbnail</h4>
<br>
<input type="file" name="thumbnail">
</div>
<div class="form-group">
<h4 style="color: black;" >Isi</h4>
<br>
<textarea class="form-control" name="message" id="" rows="10"></textarea>
</div>
<div class="form-group">
<button class="pull-right site-btn" type="submit" >Upload<img src="../public/asset/img/icons/double-arrow.png" alt="#"/></button>
</div>
</form>
and this is my view to display the data from database
#foreach ($blogs as $blog)
<div class="blog-item">
<div class="blog-thumb">
<img src="asset/img/blog/1.jpg" alt=""> ->this is where i was supposed to fetch the image
</div>
<div class="blog-text text-box text-white">
<div class="top-meta">{{ Carbon\Carbon::parse($blog->created_at)->format('d-m-Y') }} / di Rakitan</div>
<h3>{{ $blog->name }}</h3>
<p>{!! \Illuminate\Support\Str::words($blog->message, 30, '...') !!}</p>
Lanjutkan Baca <img src="asset/img/icons/double-arrow.png" alt="#"/>
</div>
</div>
#endforeach
try to add this in controller
$blog = new Blog;
$blog->name = $request->name;
$blog->message = $request->message;
if($request->hasFile('thumbnail')) {
$file = Input::file('thumbnail');
//getting timestamp
$timestamp = str_replace([' ', ':'], '-', Carbon::now()->toDateTimeString());
$name = $timestamp. '-' .$file->getClientOriginalName();
$file->move(public_path().'/images/', $name);
$blog->thumbnail = url('/images/' . $name);
}
$blog->save();
return back();
than in your view
#foreach ($blogs as $blog)
<div class="blog-item">
<div class="blog-thumb">
<img src="{{ $blog->thumbnail }}" alt=""> ->this is where i was supposed to fetch the image
</div>
<div class="blog-text text-box text-white">
<div class="top-meta">{{ Carbon\Carbon::parse($blog->created_at)->format('d-m-Y') }} / di Rakitan</div>
<h3>{{ $blog->name }}</h3>
<p>{!! \Illuminate\Support\Str::words($blog->message, 30, '...') !!}</p>
Lanjutkan Baca <img src="asset/img/icons/double-arrow.png" alt="#"/>
</div>
</div>
#endforeach
The problem with your code, I think in your store function, you did not save it correctly. Please see my code below to save link of your thumbnail into db.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Blog;
class BlogController extends Controller{
//some your function goes here
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$blog = new Blog;
$blog->name = $request->input('name');
$blog->message = $request->input('message');
$file = $request->file('your_thumbnail');
//make sure yo have image folder inside your public
$destination_path = 'image/';
$profileImage = date("Ymd").".".$file->getClientOriginalName();
$file->move($destination_path, $profileImage);
//save the link of thumbnail into myslq database
$blog->thumbnail = $destination_path . $profileImage;
$blog->save();
return redirect()->back();
}
}
This is my form
#extends('layout.template')
#section('content')
<h1>Add Student</h1>
{!! Form::open(array('action' => 'studentController#save', 'files'=>true)) !!}
<div class="form-group">
{!! Form::label('Profile-Picture', 'Profile Picture:') !!}
{!! Form::file('image',null,['class'=>'form-control']) !!}
</div>
<div class="form-group">
{!! Form::submit('Save', ['class' => 'btn btn-primary form-control']) !!}
</div>
{!! Form::close() !!}
#stop
This is my controller method
public function save()
{
$students=Request::all();
students::create($students);
Session::flash('flash_message', 'Record successfully added!');
return redirect('students');
}
when i upload image and submit image than in the database column field save this image address "/tmp/phpFFuMwC";
That' s because you are saving the temporarily generated file url.
For files you need to manually save it to the desired location
( make sure it passes validations ):
$request->file('photo')->move($destinationPath);
// With a custom filename
$request->file('photo')->move($destinationPath, $fileName);
and then store the new filename ( with or without the path ) in the database something like this:
$students = new Students;
$students->image = $fileName;
...
$students->save();
Docs: https://laravel.com/docs/5.2/requests#files
On your controlller make these changes
public function save(Request $request)
{
$destination = 'uploads/photos/'; // your upload folder
$image = $request->file('image');
$filename = $image->getClientOriginalName(); // get the filename
$image->move($destination, $filename); // move file to destination
// create a record
Student::create([
'image' => $destination . $filename
]);
return back()->withSuccess('Success.');
}
Don't forget to use
use Illuminate\Http\Request;
My form is as follow
{{ Form::open(array( 'enctype' => 'multipart/form-data'))}}
<div class="vendor-box-wrap">
<div class="page3-suggested-cat-wrap" style="float: left;width: 100%;border-bottom: 1px dotted;padding-bottom: 10px;margin-left: 20px;">
<label style="width:9%;" for="9009" class="page3-suggested-cat-label" >BoQ</label>
<div class="input-group" style="margin-top: 10px;
width: 70%;">
<span class="form-control"></span>
<span class="input-group-btn">
<span class="btn btn-primary" onclick="$(this).parent().find('input[type=file]').click();">Browse</span>
<input name="file|90009|107" id="file|9009"
value="" onchange="$(this).parent().parent().find('.form-control').html($(this).val().split(/[\\|/]/).pop());"
style="display: none;" type="file">
</span>
</div>
</br> <center><h2><strong>OR</strong></h2></center>
</div>
</div>
<div class="next-btn-wrap"><div class="cf"></div>
<div class="back-btn-wrap">
{{ Form::submit('Back',array('class' => 'back-btn', 'name' => 'back'))}}
</div>
<div class="save-btn-wrap">
{{ Form::submit('Save',array('class' => 'save-btn','name' => 'save'))}}
</div>
{{ Form::submit('Next',array('class' => 'next-btn','name' => 'next'))}}
</div>
{{ Form::close()}}
and in my controller I am using following code to get the data
$aa = Input::except(array('_token','back','save','next'));
//dd($aa);
foreach ($aa as $key=>$value){
$ids = explode("|",$key);
if(isset($ids[0]) && $ids[0]=="file" ){
$userid = Session::get('userid');
$event = Session::get('event');
$fileTblObj = new fileHandler();
$ans = Answer::find($ids[2]);
if(isset($aa[$key])){
//dd($aa[$key]);
if(Input::file($key)->isValid()) {
$destinationPath = 'app/uploads/'.$event.'/'.$userid.'/'.$pageNo ; // upload path
$extension = Input::file($key)->getClientOriginalExtension(); // getting image extension
$name = Input::file($key)->getClientOriginalName();
$curFilesize = Input::file($key)->getClientSize();
$mime =Input::file($key)->getMimeType();
if (!File::exists($destinationPath."/boq-".$name)){
//creating details for saving inthe file_handler Table
$fileTblObj->user_id = $userid;
$fileTblObj->eventName = $event ;
$fileTblObj->fileName = "boq-".$name;
$fileTblObj->formPage =$pageNo ;
$fileTblObj->filePath = $destinationPath."/";
$fileTblObj->mime= $mime;
$ans->answer_text = 'Yes';
Input::file($key)->move($destinationPath, "boq-".$name); // uploading file to given path
//Input::file($key)->move($boqPath, $boqname); // uploading file to given path
//Save filedetails
$fileTblObj->save();
$ans->save();
Session::flash('success', 'Upload successfully');
}else if(File::size($destinationPath."/".$name) != $curFilesize){
$fileDtls = $fileTblObj->where('uid',$userid)->where('fileName',$name)->where('formPage',$pageNo)->first();
Input::file($key)->move($destinationPath, $name);
$ans->answer_text = 'Yes';
$ans->save();
$fileTblObj->where('id',$fileDtls->id)->update(array('updated_at'=>date("Y-m-d h:m:s",time())));
}
//return Redirect::to('upload');
}
}
else
{
if($ans->answer_text =='')
{
$ans->answer_text = 'No';
$ans->save();
}
}
}
My problem is I am not able to get the file details on the back-end
the if statement
if(isset($ids[0]) && $ids[0]=="file" ){
}
is always false .
Any Idea How I can fix this. I also tried changing the The FOrm function to
{{ Form::open(array('files' => true)) }}
Still its not showing the file details
To send a file, I personally use this methods.
View:
{!! Form::open(array('action' => 'TestController#store', 'method' => 'POST', 'files'=>true)) !!}
{!! Form::file('thefile') !!}
{!! Form::submit('Save', array('class' => 'btn')) !!}
{!! Form::close() !!}
Controller:
$thefile = Input::file('thefile');
Hope this helps!
I want to upload (and update) an image via Laravel.
I want an existing image name in my database to be replaced by a new one.
So I have this in my controller:
public function UpdatePic()
{
$rules = array(
'image' => 'required',
);
$random = str_random(40);
$validator = Validator::make(Input::all(), $rules);
//process the storage
if ($validator->fails())
{
Session::flash('error_message', 'Fout:' . $validator->errors());
return Redirect::to('admin/user#tab_2-2')->withErrors($validator);
}else{
//define the new random generated string for imagename
$imagename = str_random(40) . '.' . Input::file('image')->getClientOriginalName();
//store
$userimg = UserImage::find(1);
$userimg->img = $imagename;
$userimg->save();
//save the image
$destinationPath = 'public/img/user_img';
if (Input::hasFile('img'))
{
$file = Input::file('img');
$file->move('public/img/user_img', $imagename);
}
//redirect
Session::flash('success', 'Uw afbeelding is succesvol veranderd!');
return Redirect::to('admin/user#tab_2-2');
}
}
The problem is, When I Got this I'm getting this error:
Creating default object from empty value
I have a post route wich one looks like this:
Route::post('updateuserpic', 'UserController#UpdatePic');
So my view looks like this:
{{ Form::open(array('url' => 'admin/updateuserpic', 'files' => true)) }}
<div class="form-group">
<div class="fileinput fileinput-new" data-provides="fileinput">
<div class="fileinput-new thumbnail" style="width: 200px; height: 150px;">
<img src="http://www.placehold.it/200x150/EFEFEF/AAAAAA&text=Geen+afbeelding" alt=""/>
</div>
<div class="fileinput-preview fileinput-exists thumbnail" style="max-width: 200px; max-height: 150px;">
</div>
<div>
<span class="btn default btn-file">
<span class="fileinput-new">
Selecteer een afbeelding
</span>
<span class="fileinput-exists">
Verander
</span>
{{ Form::file('image') }}
</span>
<a href="#" class="btn red fileinput-exists" data-dismiss="fileinput">
Verwijder
</a>
</div>
</div>
<div class="clearfix margin-top-10">
<span class="label label-danger">
waarschuwing!
</span>
<span>
Dit is enkel ondersteund in de laatste versies van Firefox, Chrome, Opera, Safari and Internet Explorer 10!
</span>
</div>
</div>
<div class="margin-top-10">
{{ Form::submit('Opslaan', array('class' => 'btn green')) }}
<a href="{{ Config::get('app.url') }}/admin/user#tab_2-2" class="btn default">
Annuleer
</a>
</div>
{{ Form::close() }}
My Class only has this stuff:
<?php
class UserImage extends Eloquent{
protected $table = 'user_image';
public $timestamps = false;
}
I think the image disappears because I'm using that route, but I don't know how to fix it... It doesn't store the image in the folder and it doesn't store the random name in the database..
Thanks people!
Kindest regards,
Robin
try:
validator::make(Input::file('image'), $rules);
and change the Input from img to image:
if (Input::hasFile('image'))
{
$file = Input::file('image');
$file->move('public/img/user_img', $imagename);
}
also to edit the data in the databse, do:
UserImage::find(1)->update(['img' => $imagename]);
no need to open a object
also your route should be
Route::post('admin/updateuserpic', 'UserController#UpdatePic');
in your blade:
{{ Form::open(array('url' => 'admin/updateuserpic','method' => 'post' ,'files' => true)) }}
Update for comment
$file = array('image' => Input::file('image');
validator::make($file , $rules);
TBH, i think your code shouldn't be so complected. your Routes are fine, try changing your controller to:
<?php
public function UpdatePic(){
//first, I'll just do the file validation
$validator = Validator::make(array( 'image' => Input::file('image')),
array('image' => 'required|image'));
if($validator->fails()){
//return error code
Session::flash('error_message', 'Fout:' . $validator->errors());
return Redirect::to('admin/user#tab_2-2')->withErrors($validator);
}else{
//update the image name
$imageName = str_random(40) . '.' . Input::file('image')->getClientOrignalName();
//store
UserImage::find(1)->update(['img' => $imageName]);
//now move that image to the new location
$file = Input::file('image');
$file->move('public/img/user_img/', $imageName);
//now we have done, lets redirect back
Session::flash('success', 'Uw afbeelding is succesvol veranderd!');
return Redirect::to('admin/user#tab_2-2');
}
}
?>
The solotion I found with some help of other people wherefor thanks!
Controller:
public function UpdatePic(){
//first, I'll just do the file validation
$validator = Validator::make(array( 'image' => Input::file('image')),
array('image' => 'required|image'));
if($validator->fails()){
//return error code
Session::flash('error_message', 'Fout:' . $validator->errors());
return Redirect::to('admin/user#tab_2-2')->withErrors($validator);
}else{
//update the image name
$imageName = str_random(40) . '.' . Input::file('image')->getClientOriginalName();
//store
UserImage::where('uid', '=', Auth::user()->id)->update(['img' => $imageName]);
//now move that image to the new location
$file = Input::file('image');
$file->move('public/img/user_img/', $imageName);
//now we have done, lets redirect back
Session::flash('success', 'Uw afbeelding is succesvol veranderd!');
return Redirect::to('admin/user#tab_2-2');
}
}
The view is just an normal input.
Hope this can help other people!
Special thanks to Ashley Wrench
I used raw PHP for the job
$source = $data['Poster']; /* URL of remote image */
$dest = "posters/".$data['Year']; /* Path */
if (!file_exists($dest)) {
mkdir($dest, 0777, true); /* Create directory */
}
$dest .= "/".$data['imdbID'].".jpg"; /* Complete file name */
/* Copy the file */
copy($source, $dest);
I'm new to Laravel. I have a form with a File upload function on it. How can I validate image file? . when i execute my code the images are getting uploaded but URL is not saved to the MySQL database, and it shows validation errors on the form as follows.
The thumbnail must be an image.
The large image must be an image.
Here's my input and validation code .
{{ Form::open(array('url' => 'admin/templates/save', 'files' => true, 'method' => 'post')) }}
#if($errors->has())
#foreach($errors->all() as $error)
<div data-alert class="alert-box warning round">
{{$error}}
×
</div>
#endforeach
#endif
<div class="row">
<div class="small-5 large-5 column">
{{ Form::label('title','Title:') }}
{{ Form::text('title',Input::old('title')) }}
</div>
</div>
<div class="row">
<div class="small-7 large-7 column">
{{ Form::label('description','Description:') }}
{{ Form::textarea('description',Input::old('description'),['rows'=>5]) }}
</div>
</div>
<div class="row">
<div class="small-7 large-7 column">
{{ Form::label('detailed_description','Detailed description:') }}
{{ Form::textarea('detailed_description',Input::old('detailed_description'),['rows'=>5]) }}
</div>
</div>
<div class="row">
<div class="small-5 large-5 column">
{{ Form::label('thumbnail','Choose thumbnail image:') }}
{{ Form::file('thumbnail') }}
</div>
</div>
<div class="row">
<div class="small-5 large-5 column">
{{ Form::label('large_image','Choose large image:') }}
{{ Form::file('large_image') }}
</div>
</div>
<div class="row">
<div class="small-5 large-5 column">
{{ Form::label('targeturl','Target URL:') }}
{{ Form::text('targeturl',Input::old('Target URL')) }}
</div>
</div>
{{ Form::submit('Save',['class'=>'button tiny radius']) }}
{{ Form::close() }}
Controller code
<?php
class TemplateController extends BaseController
{
public function newTemplate()
{
$this->layout->title = 'New Template';
$this->layout->main = View::make('dash')->nest('content', 'templates.new');
}
public function saveTemplate() {
//TODO - Validation
$destinationPath = '';
$filename = '';
$destinationThumb = '';
$thumbname = '';
$thumb = Input::file('thumbnail');
$destinationThumb = public_path().'/thumb/';
$thumbname = str_random(6) . '_' . $thumb->getClientOriginalName();
$uploadSuccess = $thumb->move($destinationThumb, $thumbname);
$file = Input::file('large_image');
$destinationPath = public_path().'/img/';
$filename = str_random(6) . '_' . $file->getClientOriginalName();
$uploadSuccess = $file->move($destinationPath, $filename);
$rules = [
'title' => 'required',
'description' => 'required',
'detailed_description' => 'required',
'targeturl' => 'required',
'thumbnail' => 'required|image',
'large_image' => 'required|image'
];
$validator = Validator::make(Input::all(), $rules);
if ($validator->passes()) {
$template = new Template();
$template->title = Input::get('title');
$template->description = Input::get('description');
$template->thunbnailURL = $destinationThumb . $thumbname;
$template->detailedDescription = Input::get('detailed_description');
$template->targetURL = Input::get('targeturl');
$template->detailImageURL = $destinationPath . $filename;
//$user->created_at = DB::raw('NOW()');
//$user->updated_at = DB::raw('NOW()');
$template->save();
return Redirect::back()->with('success', 'Template added!');
} else
return Redirect::back()->withErrors($validator)->withInput();
}
}
Please help me.
Move your upload code inside validation passes
public function saveTemplate() {
//TODO - Validation
$rules = [
'title' => 'required',
'description' => 'required',
'detailed_description' => 'required',
'targeturl' => 'required',
'thumbnail' => 'required|image',
'large_image' => 'required|image'
];
$validator = Validator::make(Input::all(), $rules);
if ($validator->passes()) {
$thumb = Input::file('thumbnail');
$destinationThumb = public_path().'/thumb/';
$thumbname = str_random(6) . '_' . $thumb->getClientOriginalName();
$uploadSuccess = $thumb->move($destinationThumb, $thumbname);
$file = Input::file('large_image');
$destinationPath = public_path().'/img/';
$filename = str_random(6) . '_' . $file->getClientOriginalName();
$uploadSuccess = $file->move($destinationPath, $filename);
$template = new Template();
$template->title = Input::get('title');
$template->description = Input::get('description');
$template->thunbnailURL = $destinationThumb . $thumbname;
$template->detailedDescription = Input::get('detailed_description');
$template->targetURL = Input::get('targeturl');
$template->detailImageURL = $destinationPath . $filename;
//$user->created_at = DB::raw('NOW()');
//$user->updated_at = DB::raw('NOW()');
$template->save();
return Redirect::back()->with('success', 'Template added!');
} else
return Redirect::back()->withErrors($validator)->withInput();
}