$slider=Slider::create($request->all()); if($request->hasFile('image')) { $image = $request->file('image'); $imageName = \Illuminate\Support\Str::random('32') . '.' . $image->getClientOriginalExtension(); //now save the image file $image->move('public/images/slider', $imageName); $slider->image = $imageName; } $slider->save(); Session::flash('flash_success','Added Slider Successfully'); return redirect('admin/slider');
Sep 29, 2019
5
Level 3
Laravel | File upload. Problem with saving into database
Hello guys, I am trying to upload file, and save into DB (in table documents)
Model Document:
class Document extends Model
{
protected $fillable = [
'filename',
'subpage_id',
];
protected $appends = ['path'];
public function getPathAttribute()
{
return asset('caritas/storage/app/'.$this->filename);
}
public $timestamps = false;
public function subpage()
{
return $this->belongsTo(Subpage::class, 'subpage_id');
}
}
ForeignKey:
Schema::table('documents', function(Blueprint $table){
$table->integer('subpage_id')->unsigned()->change();
$table->foreign('subpage_id','documents_subpage_id_foreign')->references('id')->on('subpages');
});
Function Store in SubpageController:
public function store(Request $request)
{
$subpage = Subpage::create($request->all());
if ($request->has('documents')){
foreach ($request->documents as $document) {
$request->validate([
'documents' => 'required|file|max:1024',
]);
$filename = "filename".time().'.'.request()->documents->getClientOriginalExtension();
$request->documents->storeAs('public/documents',$filename);
Document::create([
'subpage_id' => $subpage->id,
'filename' => $filename
]);
}
}
return redirect()->action('SubpageController@slist');
}
fragment of create.blade.php view:
<input type="file" id="uploadDocument" onchange="ValidateFileSize(this)" name="documents[]" multiple aria-describedby="fileHelp"/>
and route:
Route::get('subpage/create','SubpageController@create')->middleware('auth');
Route::post('subpage/', 'SubpageController@store')->middleware('auth');
I'm not sure, but it's probably the controller function problem. I don't get any error, but the file is not saved in the database. I have empty records Could someone help me figure out where I am making a mistake? Thanks.
Level 60
foreach ($request->documents as $document) {
// $document, not $request->documents
$filename = 'filename'.time().'.'.$document->getClientOriginalExtension();
// once again, $document, not $request->documents
$document->storeAs('public/documents',$filename);
Document::create();
}
Please or to participate in this conversation.