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