Hi @pontiacgtx
Could you post your Post Model code please?
Just in case...are you using protected $fillable at that model?
If that's the case, be sure that you've added the new cover_image field.
I have followed some video tutorial to learn laravel but I find a problem when trying to save the image file from an action in the controller posts where it doesnt set a path to the image but there is an existing image so I wonder why this database insertion doesnt work? it is worth noting that there is a CKEDITOR script where the body text area is but I dont know if there is some problem when calling $request->hasFile('photo') if i use that editor
the code for the migration
public function up()
{
Schema::table('posts', function (Blueprint $table) {
$table->string('cover_image');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('posts', function (Blueprint $table) {
$table->dropColumn('cover_image');
});
}
the code for the action
public function update(Request $request, $id)
{
$this->validate($request,
[
'title'=>'required',
'body'=> 'required',
'photo.*'=> 'image|max:1999'
]);
//handle file upload
if($request->hasFile('photo'))
{
//get file nae with extension
$filenameWithExte = $request->file('photo')->getClientOriginalName();
//get the filename
$filename =pathinfo($filenameWithExte,PATHINFO_FILENAME);
$extension = $request->file('photo')->getClientOriginalExtension();
//final name to store in db
$fileNameToStore =$filename.'_'.time().'.'.$extension;
// upload the image //require creating the folder public/cover image first;
$path =$request->file('photo')->storeAs('public/cover_images',$fileNameToStore);
}
else
{
$fileNameToStore = 'noimage.jpg'; //set a default static image for no image uploaded
}
$post = Post::find($id);
$post->title = $request->input('title');
$post->body = $request->input('body');
$post->user_id= auth()->user()->id;
$post->cover_image = $fileNameToStore;
$post->save();
return redirect('/posts')->with('success','Post updated');
}
the view
@section('body')
<br/>
<h1>Create new Post </h1>
{!! Form::open(['action'=>'PostController@store','method'=>'POST','enctype'=> 'multipart/form-data','files' => true]) !!}
<div class="form-group">
{{Form::label('title','Title')}}
{{ Form::text('title','',['class','form-control','placeholder'=> 'Title']) }}
</div>
<div class="form-group">
{{Form::label('body','Body')}}
{{ Form::textarea('body','',['id'=> 'editor','class','form-control','placeholder'=> 'Body text']) }}
</div>
<div class="form-group">
{{Form::file('photo')}}
</div>
{{Form::submit('Submit',['class'=> 'btn btn-primary'])}}
{{ Form::close() }}
<script>
ClassicEditor
.create(document.querySelector('#editor'))
.catch(error=>{
console.error(error);
});
</script>
@endsection
Please or to participate in this conversation.