Laravel - File Input Array Update - php

I want to update my file input images, but as soon as I update 1 image the other images are removed why is that? I want to left them as what they are when they had been upload. help me please thanks.
Here is an image of the problem
Controller
Update, public function, here is where I put the logic of the code
public function update(Request $request, $id)
{
$this->validate($request, [
'inflightmagz_date' => 'required',
'infightmagazine_pdf.*' => 'image|nullable|max:1999'
]);
$inflightmags = [];
if ($request->has('infightmagazine_pdf'))
{
//Handle File Upload
foreach ($request->file('infightmagazine_pdf') as $key => $file)
{
// Get FileName
$filenameWithExt = $file->getClientOriginalName();
//Get just filename
$filename = pathinfo( $filenameWithExt, PATHINFO_FILENAME);
//Get just extension
$extension = $file->getClientOriginalExtension();
//Filename to Store
$fileNameToStore = $filename.'_'.time().'.'.$extension;
//Upload Image
$path = $file->storeAs('public/infightmagazine_pdfs',$fileNameToStore);
array_push($inflightmags, $fileNameToStore);
}
$fileNameToStore = serialize($inflightmags);
}
$inflightmagContent = InflightMagazine::find($id);
$inflightmagContent->inflightmagz_date = $request->input('inflightmagz_date');
foreach ($inflightmags as $key => $value) {
$implodedInflight = implode(' , ', $inflightmags);
if($request->hasFile('infightmagazine_pdf')){
$inflightmagContent->infightmagazine_pdf = $implodedInflight;
}
}
$inflightmagContent->save();
return redirect('/admin/airlineplus/inflightmagazines')->with('success', 'Content Updated');
}
View, edit.blade.php
{!! Form::open(['action'=>['Admin\FleetsController#update',$fleet->id], 'method' => 'POST','enctype'=>'multipart/form-data', 'name' => 'add_name', 'id' => 'add_name']) !!}
<div class="table-responsive">
<table class="table table-bordered" id="dynamic_field">
<tr>
<td> {{Form::text('title', $fleet->title, ['class' => 'form-control', 'placeholder' => 'Enter a Title', 'id'=>"exampleFormControlFile1"])}}<br>
{{Form::textarea('description', $fleet->description, ['class' => 'form-control', 'placeholder' => 'Enter a Description'])}} <br>
<div class="card card-body col-md-8">
#foreach(explode(' , ' ,$fleet->fleet_image) as $content)
<img src="{{ asset('storage/fleet_images/' . $content) }}" style="width:50px;height:50px;"><br/>
{{ Form::file('fleet_image[]',['id'=>'exampleFormControlFile1']) }}<br/>
#endforeach
</div>
</td>
</tr>
</table>
{{Form::hidden('_method', 'PUT')}}
{{Form::submit('submit', ['class'=>'btn btn-primary', 'name'=>'submit'])}}
</div>
{!! Form::close() !!}

try this code
add if condition like if($request->hasFile('infightmagazine_pdf') && !empty($implodedInflight) && isset($implodedInflight)) this
//Handle File Upload
foreach ($request->file('infightmagazine_pdf') as $key => $file)
{
if ($file->has('infightmagazine_pdf'))
{
// Get FileName
$filenameWithExt = $file->getClientOriginalName();
//Get just filename
$filename = pathinfo( $filenameWithExt, PATHINFO_FILENAME);
//Get just extension
$extension = $file->getClientOriginalExtension();
//Filename to Store
$fileNameToStore = $filename.'_'.time().'.'.$extension;
//Upload Image
$path = $file->storeAs('public/infightmagazine_pdfs',$fileNameToStore);
array_push($inflightmags, $fileNameToStore);
$fileNameToStore = serialize($inflightmags);
}
}
$inflightmagContent = InflightMagazine::find($id);
$inflightmagContent->inflightmagz_date = $request->input('inflightmagz_date');
foreach ($inflightmags as $key => $value) {
$implodedInflight = implode(' , ', $inflightmags);
if($request->hasFile('infightmagazine_pdf') && !empty($implodedInflight) && isset($implodedInflight)){
$inflightmagContent->infightmagazine_pdf = $implodedInflight;
}
}
$inflightmagContent->save();
return redirect('/admin/airlineplus/inflightmagazines')->with('success', 'Content Updated');

Related

Issue with: Upload image Database Laravel "c:\xampp\tmp\php.tmp"

I'm confused again, if im trying to upload a image im my database. The name of the image is given with a tmp file like this "C:\xampp\tmp\phpB001.tmp". What is the solution to this Issue.
Controller: AdminLeistungController.php
public function store(Request $request)
{
$data = $this->_validate($request);
$data['creator_id'] = auth()->user()->id;
if($request->hasfile('image')){
$fileameWithExt = $request->file('image')->getClientOriginalName();
$filename = pathinfo($fileameWithExt, PATHINFO_FILENAME);
$extension = $request->file('image')->getClientOriginalExtension();
$fileNameToStore = $filename . '_' . time() . '.' . $extension;
$path = $request->file('image')->storeAs('uploads/leistungen', $fileNameToStore);
} else {
$fileNameToStore = 'noimage.jpg';
}
Leistungen::create($data);
return redirect(route('admin.leistung.index'))->withSuccess('Successfully');
}
private function _validate($request)
{
$rules = [
'title' => 'required',
'article' => 'required|min:3',
'seo_title' => 'required',
'seo_description' => 'required',
'image' => 'mimes:jpeg,png|max:1014',
];
return $this->validate($request, $rules);
}
public function update(Request $request, Leistungen $leistung)
{
$data = $this->_validate($request);
$leistung->update($data);
return redirect(route('admin.leistung.index'))->withSuccess('Successfully');
}
Controller: create.blade.php
<form enctype="multipart/form-data" action="{{route('admin.leistung.store')}}" method="post" enctype="multipart/form-data" class="col-lg-12">
#include('admin.leistung._form')
...
Controller: _form.blade.php
<input type="file" id="image" name="image" value="{{old('image') ?? $leistung->image ?? ''}}" class="form-control #if($errors->has('image')) is-invalid #endif">

How To Create Multiple Upload Files with 2 input file

I will create multiple upload file with 2 input file but i don't know
Fields.blade.php
<div class="form-group col-sm-6" id="cover">
{!! Form::label('cover', 'Cover:') !!}
{!! Form::file('cover', null, ['class' => 'form-control']) !!}
</div>
<div class="form-group col-sm-6" id="full">
{!! Form::label('full', 'Full:') !!}
{!! Form::file('full', null, ['class' => 'form-control']) !!}
</div>
CatalogController.php
public function createWithCategory($id)
{
$katalog_metadata = KatalogMetadata::with('metadata')->where('category_id', $id)->get();
return view('catalogs.create')->with('katalog_metadata', $katalog_metadata)->with('category_id', $id);
}
public function store(CreateCatalogRequest $request)
{
$input = $request->all();
if (Auth::user()->can('isAdmin')) {
$input['status'] = 1;
} else {
$input['status'] = 0;
}
$input['cover'] = $this->uploadingCover($request);
$input['full'] = $this->uploadingFull($request);
$catalog = $this->catalogRepository->create($input);
foreach ($input['metadata'] as $key => $value) {
$val = [
'metadata_id' => $key,
'metadata_key' => $value['key'],
'value' => $value['value'],
'catalog_id' => $catalog->id
];
$data = new CatalogMetadataValue($val);
$catalog->catalog_metadata_value()->save($data);
}
if (!Auth::user()->can('isAdmin')) {
$admin = User::where('role_id', '1')->first();
Mail::to($admin->email)->send(new NotifyNewCatalog($catalog));
}
Flash::success('Catalog saved successfully.');
return redirect(route('catalogs.index_with_category', $request->category_id));
}
protected function uploadingCover($request)
{
$destinationPath = 'catalog/cover';
if (!is_dir($destinationPath)) {
if (!is_dir('catalog')) {
mkdir('catalog');
}
mkdir($destinationPath);
}
if ($request->hasFile('cover')) {
$file = $request->file('cover');
$fileName = time() . '.' . $file->getClientOriginalExtension();
$file->move($destinationPath, $fileName);
return $destinationPath . '/' . $fileName;
}
return;
}
protected function uploadingFull($request)
{
$destinationPath = 'catalog/full';
if (!is_dir($destinationPath)) {
if (!is_dir('catalog')) {
mkdir('catalog');
}
mkdir($destinationPath);
}
if ($request->hasFile('full')) {
$file = $request->file('full');
$fileName = time() . '.' . $file->getClientOriginalExtension();
$file->move($destinationPath, $fileName);
return $destinationPath . '/' . $fileName;
}
return;
}
Thanks
File element name should be in array and add multiple keyword.
i.e {!! Form::file('cover[]', null, ['class' => 'form-control','multiple'])
!!}
In controller do the upload with array data
if ($request->hasFile('cover')) {
foreach($request->file('cover') as $file)
{
$fileName = time() . '.' . $file->getClientOriginalExtension();
$file->move($destinationPath, $fileName);
$data[] = $name;
}
}

Creating default object from empty value when updating record

I can create a new record in my DB fine but when I update using the below code I get error "Creating default object from empty value"
public function update(Request $request, $id)
{
$gameSearch = Game::findOrFail($id);
if($file = $request->file('image')){
$name = $file->getClientOriginalName();
if($file->move('images/games/', $name)){
$games->image = 'images/games/' . $name;
$games->title = $request->title;
$games->price = $request->price;
$games->category_id = $request->category_id;
$games->promote = $request->promote;
$games->sold = 0;
$games->save();
return redirect()->route('admin.games');
};
};
}
Route:
Route::resource('/admin/games', 'AdminGamesController', [
'names'=>[
'index'=>'admin.games.index',
'create'=>'admin.games.create',
'store'=>'admin.games.store',
'edit'=>'admin.games.edit',
'show'=>'admin.games.show',
'destroy'=>'admin.games.destroy',
]]);
Form:
{!! Form::model($gameSearch, ['method' =>'PATCH', 'action'=> ['AdminGamesController#update', $gameSearch->id], 'files'=>true, 'enctype'=>'multipart/form-data']) !!}
<div class="form-group {{$errors->has('title') ? 'has-error' : ''}}">
{!! Form::label('title', 'Game Title:') !!}
{!! Form::text('title', null, ['class'=>'form-control', 'rows' => 3])!!}
#if($errors->has('title'))
{{$errors->first('title')}}
#endif
</div>
<div class="form-group {{$errors->has('image') ? 'has-error' : ''}}">
{!! Form::label('image', 'Image:') !!}
{!! Form::file('image', null, ['class'=>'form-control'])!!}
#if($errors->has('image'))
{{$errors->first('image')}}
#endif
</div>
If I use this code however it works but doesn't handle updating the link to the image at all
public function update(GamesRequest $request, $id)
{
$gameSearch = Game::findOrFail($id);
$input = $request->all();
if($file = $request->file('image')){
$name = $file->getClientOriginalName();
$file->move('images/games/', $name);
}
$gameSearch->update($input);
return redirect('admin/games');
}
$gameSearch Vs. $games. You load your object from the DB into $gameSearch but then, try to populate and save $games. Change all references of $games to $gameSearch.
public function update(Request $request, $id)
{
$gameSearch = Game::findOrFail($id);
if ($file = $request->file('image')) {
$name = $file->getClientOriginalName();
if ($file->move('images/games/', $name)) {
$gameSearch->image = 'images/games/' . $name;
$gameSearch->title = $request->title;
$gameSearch->price = $request->price;
$gameSearch->category_id = $request->category_id;
$gameSearch->promote = $request->promote;
$gameSearch->sold = 0;
$gameSearch->save();
return redirect()->route('admin.games');
};
};
}

How can I update image in edit view in laravel?

In laravel I have a field in my edit view named Profile Picture, whenever I click On edit button I got all the values from database in edit view but I don't get image, And If whenever I click on submit button everytime I have to upload image without that I can't process further I want If I not upload new image then form will automatic consider old profile pic
my blade file is like
<div class="col-md-6">
<div class="form-group">
<label for="photo">Profile Picture :<span class="danger">*</span> </label>
<div class="row">
<div class="col-md-9">
<input type="file" class="form-control" id="file" name="file">
</div>
<div class="col-md-3">
#foreach ($empProfilePic as $empProfilePicture)
#if($employee->id == $empProfilePicture->id)
<img src="uploads/images/{{ $empProfilePicture->file }}" id="profile-img-tag" height="100" width="100">
#endif
#endforeach
</div>
</div>
</div>
</div>
Controller File
public function updateEmployee(Request $request, $id)
{
$employee = User::find($id);
//Get inputs for personal detail
$firstName = $request->get('firstName');
$middleName = $request->get('middleName');
$lastName = $request->get('lastName');
$gender = $request->get('gender');
$city = $request->get('city');
$state = $request->get('state');
$localAddress = $request->get('localAddress');
$permanentAddress = $request->get('permanentAddress');
$personalEmail = $request->get('personalEmail');
$mobileNumber = $request->get('mobileNumber');
$companyEmail = $request->get('companyEmail');
$empId = $request->get('empId');
$department = $request->get('department');
$designation = $request->get('designation');
$status = $request->get('status');
$totalExperience = $request->get('totalExperience');
$aboutMe = $request->get('aboutMe');
$roleName = $request->get('role');
$role = $request->get('role');
if ($role == 'hr')
{
$role = '5c8a51ed650fbd5398503043';
}
else
{
$role = '5c8a51ed650fbd5398503044';
}
// //Store Image In Folder
$file = $request->file('file');
$name = $file->getClientOriginalName();
$file->move('uploads/images', $name);
if (file_exists(public_path($name = $file->getClientOriginalName())))
{
unlink(public_path($name));
};
$accountHolderName = $request->get('accountHolderName');
$accountNumber = $request->get('accountNumber');
$bankName = $request->get('bankName');
$ifscCode = $request->get('ifsc_code');
$panNumber = $request->get('panNumber');
$branchName = $request->get('branchName');
//Enter in database
$employee->role_id = $role;
$employee->role_name = $roleName;
$employee->username = $firstName;
//Update Image
$employee->file = $name;
$employee->personal_email = $personalEmail;
$employee->company_email = $companyEmail;
$employee->status = $status;
$personalDetail = ([
'emp_id' => $empId,
'first_name' => $firstName,
'middle_name' => $middleName,
'last_name' => $lastName,
'gender' => $gender,
'city' => $city,
'state' => $state,
'local_address' => $localAddress,
'permanent_address' => $permanentAddress,
'personal_email' => $personalEmail,
'mobile_number' => $mobileNumber,
'department' => $department,
'designation' => $designation,
'total_experience' => $totalExperience,
'about_me' => $aboutMe,
]);
$bankDetail = ([
'account_holder_name' => $accountHolderName,
'account_number' => $accountNumber,
'bank_name' => $bankName,
'ifsc_code' => $ifscCode,
'pan_number' => $panNumber,
'branch_name' => $branchName,
]);
$employee->status = $status;
$employee->personal_detail = $personalDetail;
$employee->bank_detail = $bankDetail;
$employee->save();
return redirect('list-of-employees')->with('Success', 'Data Updated Successfully!');
}
Will anyone will help, Thank you in advance
In controller:
Code for update file:
Its update only when you select a file for the update.
Here I use the Employee model you can replace with your model
public function update(Request $request, $id){
$employee = Employee::find($id);
if($request->file != ''){
$path = public_path().'/uploads/images/';
//code for remove old file
if($employee->file != '' && $employee->file != null){
$file_old = $path.$employee->file;
unlink($file_old);
}
//upload new file
$file = $request->file;
$filename = $file->getClientOriginalName();
$file->move($path, $filename);
//for update in table
$employee->update(['file' => $filename]);
}
}
Try this. If you get the file in post method, only then set the file variable of an employee.
// //Store Image In Folder
if (isset($_FILES['file'])) {
$file = $request->file('file');
$name = $file->getClientOriginalName();
$file->move('uploads/images', $name);
if (file_exists(public_path($name = $file->getClientOriginalName())))
{
unlink(public_path($name));
};
//Update Image
$employee->file = $name;
}
//Enter in database
$employee->role_id = $role;
$employee->role_name = $roleName;
$employee->username = $firstName;
Make the image input optional (don't add required) on the blade file and on the validation (controller) then check before updating as:
if ($request->hasFile('image')) {
// Perform image update
}

Multiple images uploaded with Laravel

I have trying to make multiple images function with Laravel but I have received
'Invalid argument supplied for foreach()'
This is the function in the controller
public function uploadSubmit() {
$files = Input::file('image');
$file_count = count($files);
$gallery = 0;
foreach($files as $file) {
$gallery = new Gallery;
$rules = array('file' => 'required');
$validator = Validator::make(array('file'=> $file), $rules);
if($validator->passes()){
$filename = str_random(20);
$file->move(public_path() . '/uploads', $filename . '.' . $file->getClientOriginalExtension());
$imagePath = '/uploads/' . $filename . '.' . $file->getClientOriginalExtension();
$image = Image::make(public_path() . $imagePath);
$image->save();
$gallery ++;
$gallery->image = $imagePath;
$gallery->save();
}
}
if($gallery == $file_count){
return Redirect::to('/admin/upload')->with('message', 'image added.');
}
else
{
return Redirect::to('/admin/upload')->withInput()->withErrors($validator);
}
}
When I var_dump($files); it returns NULL.
The form is
{{ Form::open() }}
{{ Form::file('image[]', array('multiple'=>true)) }}
<hr />
<button type="submit" class="btn btn-primary">upload</button>
{{ Form::close() }}
My route:
Route::get ('/admin/upload', ['uses' => 'AdminController#upload', 'before' => 'admin']);
Route::post('/admin/upload', ['uses' => 'AdminController#uploadSubmit', 'before' => 'csrf|admin']);
make File true when you create your form
{!! Form::open(array('route' => 'image.upload', 'method' => 'POST',
'files' => true)) !!}
{!! Form::open(array('route' => 'image.upload', 'method' => 'POST', 'files' => true)) !!}
{{ Form::file('image[]', array('multiple'=>true)) }}
<hr />
<button type="submit" class="btn btn-primary">upload</button>
{{ Form::close() }}
Your Function
public function uploadSubmit() {
$files = Input::file('image');
$file_count = count($files);
foreach($files as $file) {
$gallery = new Gallery;
$rules = array('file' => 'required');
$validator = Validator::make(array('file'=> $file), $rules);
if($validator->passes()){
$filename = str_random(20). '.' . $file->getClientOriginalExtension();
$file->move('uploads', $filename );
$gallery->image = $filename;
$gallery->save();
}
}
}

Categories