How To Create Multiple Upload Files with 2 input file - php

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;
}
}

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">

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');
};
};
}

Laravel - File Input Array Update

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');

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();
}
}
}

Laravel 5 Image Upload Incorrect Database Path

I have been having issues with my image upload input. I am attempting to create a file upload input into my Laravel 5 project but I am running into problems with the path that is saved into the database image table.
The form is working and is posting, however, when the database saves the path to the image it is inputting: /Applications/MAMP/tmp/php/phptvwTYW instead of taking just the file name.
Additionally, the file is being moved to the correct public/img folder.
Code
public function store(PostRequest $request)
{
$this->createPost($request);
$destinationpath = public_path() . '/img/';
$filename = $request->file('image_url')->getClientOriginalName();
$request->file('image_url')->move( $destinationpath,$filename );
flash()->success('Your Post Has Been Created!');
return redirect('posts');
}
Here is the sample Controller Function currently using in my project
public function postCreateInternal(CreateDocumentInternalRequest $request) {
$data_information = $request->only(['title', 'assigned_to', 'folder_id', 'document_source']);
if ($request->hasFile('file_name') && $request->file('file_name')->isValid()) {
$document = $request->file('file_name');
#creating file Name
$mytime = Carbon::now();
$date_now = $mytime->toDateTimeString();
$date_now = $this->prepareFileNameString($date_now);
$document_extension = $document->getClientOriginalExtension();
$document_name = $this->prepareFileNameString(basename($document->getClientOriginalName(), '.' . $document_extension));
$document_fullName = $document_name . "_" . ($date_now) . "." . $document_extension;
$data_information['file_type'] = $document->getMimeType();
$data_information['file_size'] = $document->getSize();
$data_information['file_name'] = $document_fullName;
$data_information['file_download_type'] = "Internal";
$document->move(public_path() . '/uploads/documents/', $document_fullName);
}
if ($pot = $this->document->create($data_information)) {
$this->notification_admin->sendCreateDocument($data_information);
return redirect()->route('documents')->with('success', trans('document.create.msg_success'));
// return redirect()->route('update/document', $pot->id)->with('success', trans('document.create.msg_success'));
}
return redirect()->route('create/document')->with('error', trans('document.msg_error'));
}
CreateDocumentInternalRequest basically using for File and other data validation as per Laravel 5
And View File seems to like:
{!! Form::open(["class"=>"form-horizontal","data-parsley-validate"=>"data-parsley-validate",'role'=>'form','files'=>true]) !!}
<div class="form-group required {{ $errors->first('file_name', ' has-error') }}">
{!!Form::label('file_name', trans('document.label.file_name'), array('class' => 'col-md-4 control-label left-label'))!!}
<div class="col-sm-6">
{!! Form::file('file_name') !!}
{!! $errors->first('file_name', '<span class="help-block">:message</span>') !!}
</div>
</div>
{!! Form::close() !!}
In my current implementation, first i'm checking file uploaded, rename filename with current timestamp and re upload my desire location.
If you need any help my provided method let me know to improve in better way.
this is very simple way:
public function store(PostRequest $request)
{
$image_name = $request->file('image')->getClientOriginalName();
$request->file('image')->move(base_path().'/public/images', $image_name);
$post = ($request->except(['image']));
$post['image'] = $image_name;
Post::create($post);
Session::flash('success_message', 'Post has been added successfully!');
return redirect('teacher');
}
public function profileUpdate($id)
{
if(!Entrust::can('profile_update_employee'))
return Redirect::to('/dashboard')->withErrors(Config::get('constants.NA'));
if(!Helper::getMode())
return Redirect::back()->withErrors(Config::get('constants.DISABLE_MESSAGE'));
$employee = User::find($id);
if(!$employee)
return Redirect::to('employee')->withErrors(Config::get('constants.INVALID_LINK'));
$rules = array(
'photo' => 'image|image_size:<=2000|max:100000',
'date_of_birth' => 'date',
'date_of_joining' => 'date',
'date_of_leaving' => 'date',
'employee_code' => 'required|unique:profile,employee_code,'.$employee->Profile->id.',id'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails())
return Redirect::to('/employee/'.$id."#basic")->withErrors($validator);
Activity::log('Profile updated');
$profile = $employee->Profile ?: new Profile;
$photo = $profile->photo;
$data = Input::all();
$profile->fill($data);
if(Input::get('date_of_birth') == '')
$profile->date_of_birth = null;
if(Input::get('date_of_joining') == '')
$profile->date_of_joining = null;
if(Input::get('date_of_leaving') == '')
$profile->date_of_leaving = null;
if (Input::hasFile('photo') && Input::get('remove_photo') != 1) {
$filename = Input::file('photo')->getClientOriginalName();
$extension = Input::file('photo')->getClientOriginalExtension();
$file = Input::file('photo')->move('assets/user/', $employee->username.".".$extension);
DB::insert('insert into ez_profile (id, photo) values ($id, $photo)');
$img = Image::make('assets/user/'.$user->username.".".$extension);
$img->resize(200, null, function ($constraint) {
$constraint->aspectRatio();
});
$img->save('assets/user/'.$user->username.".".$extension);
$profile->photo = $employee->username.".".$extension;
} elseif(Input::get('remove_photo') == 1){
File::delete('assets/user/'.$profile->photo);
$profile->photo = null;
}
else
$profile->photo = $photo;
$employee->profile()->save($profile);
return Redirect::to('/employee/'.$id.'/#basic')->withSuccess(Config::get('constants.SAVED'));
}
Try this:
public function store(PostRequest $request, Post $post) {
$destinationpath = public_path() . '/img/';
$filename = $request->file('image_url')->getClientOriginalName();
$request->file('image_url')->move( $destinationpath,$filename );
$post->create([
'field1' => $val1,
'imageField' => $filename,
'field2' => $val2
]);
flash()->success('Your Post Has Been Created!');
return redirect('posts');
}
I found the solution to my question.
I had to make some changes to the store and createPost functions within my controller to make this work.
For the controller I have:
public function store(PostRequest $request)
{
$destinationpath = public_path() . '/img/';
$filename = $request->file('image_url')->getClientOriginalName();
$request->file('image_url')->move( $destinationpath,$filename );
$this->createPost($request, $filename);
flash()->success('Your Post Has Been Created!');
return redirect('posts');
}
private function createPost(PostRequest $request, $new_url)
{
$post = Auth::user()->posts()->create($request->all());
$post->image_url = $new_url;
$post->save();
$this->syncTags($post, $request->input('tag_list'));
return $post;
}
I hope this helps anyone else that may be running into this same problem.
Thank you everyone for the help!
its because you save before moving,
//before moving
$request->file('image_url')->getPath(); // returns Applications/MAMP/tmp/php/php...
to have the full path of your new moved file you can do this
//After moving
$res = $request->file('image_url')->move( $destinationpath,$filename );
$my_new_path = $res->getPath(); // returns [public_path]/img/filename.jpg
you can save it by update your post after moving the file, or use event to move it when saving
look here http://laravel.com/docs/master/eloquent#events

Categories