I've built something that I would expect to work. It should upload the file and replace the 'attachment' entry for the record with the new file's path. Here is the method:
public function update($id)
{
$article = Article::find($id);
$article->username = Session::get('username');
$article->body = Input::get('body');
$article->title = Input::get('title');
if(Input::hasFile('attachment'))
{
$file = Input::file('attachment');
$name = time() . '-' . $file->getClientOriginalName();
$file = $file->move(public_path() . '/documents/articles/', $name);
$article->attachment = $name;;
}
$article->save();//Commit this edit to the database
return Redirect::route('articles.index');
}
And the form:
<div class="form-general">
{{ Form::model($article, array('route' => array('articles.update', $article->id, 'files' => true), 'method' => 'PUT')) }}
<div>
{{ Form::label('title', 'Title:') }}
{{ Form::text('title', null, array('class' => 'form-control' )) }}
</div>
<br />
<div>
@if(! empty($article->attachment))
{{ Form::label('attachment', 'Attachment:') }} <br />
<div class="attachment-replace" style="display:none;">
{{ Form::file('attachment', null, array('class' => 'form-control' )) }}
</div>
<a class="current-attachment" href="/documents/articles/{{ $article->attachment }}">{{ $article->attachment }}</a> <a href="#" class="current-attachment"><span class="glyphicon glyphicon-remove-circle remove-attachment"></span></a>
@else
{{ Form::label('attachment', 'Attachment:') }}
{{ Form::file('attachment', null, array('class' => 'form-control' )) }}
@endif
</div>
<br />
<div>
{{ Form::label('body', 'Body:') }}
{{ Form::textarea('body', null, array('class' => 'form-control' )) }}
</div>
<br />
<div>{{ Form::submit('Edit Post', array('class' => 'btn btn-default')) }}</div>
{{ Form::close() }}
</div>
Currently, nothing happens. The method gets executed and the other fields update fine, but the attachment does not. It seems that the File input "attachment" never even gets set. How can I properly update a file path and upload its replacement document at once?
Your files
parameter is part of the wrong array. You have this line, which opens your form :
{{ Form::model($article, array('route' => array('articles.update', $article->id, 'files' => true), 'method' => 'PUT')) }}
If you look closely, you will find that the files => true
option is part of your route
array, however it should be outside of it. Like so :
{{ Form::model($article, array('route' => array('articles.update', $article->id), 'files' => true, 'method' => 'PUT')) }}
As they say, the devil is in the details ;)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.