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

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

Related

How to add file in laravel through dropify data-default-file

Hello i am trying to show the image in the dropify field by fetching the image from database.But i am unable to do so .Kindly check my code.
`
<input type="file" class="dropify" name="profile_pic" data-default-file="{{ url('/uploads/driving/'.$user->profile_pic) }}"/>
THE CONTROLLER IS
public function editUserForm($id)
{
$user = User::find($id);
return view('admin.users.edit-users',compact('user'));
}
public function updateUser(Request $request,$id)
{
$r1 = $request->validate([
'profile_pic' => 'required|image|mimes:jpg,png,jpeg,gif,svg|max:2048|',
'name' => 'required',
'email' => 'required|email',
'city' => 'required',
'phone_no' => 'required',
]);
if ($request->hasFile('profile_pic')) {
$imgName = uniqid() . '.' . $request->profile_pic->getClientOriginalExtension();
}
$user = User::find($id);
$user->name = $request->name;
$user->email = $request->email;
$user->phone_no = $request->phone_no;
$user->profile_pic =$imgName;
$user->city = $request->city;
$user->update();
$path = public_path('uploads/driving');
if ($request->hasFile('profile_pic')) {
$request->profile_pic->move($path, $imgName);
}
return redirect()->route('users')->with('message', 'User info updated successfully!');
}
i created a url data-default-file="{{ url('/uploads/driving/'.$user->profile_pic) }}" but unable to show the image.

Intervention image multiple image upload in laravel

in blade
<input type="file" name="image[]" id="" required class="form-control" multiple accept="image/*">
in controller
public function addReviewPost(Request $request)
{
$image = $request->file('image');
$this->validate($request, [
'image' => 'required',
'image.*' => ' max:2048 | dimensions:max_width=2200',
]);
if (request()->hasFile('image')) {
$counter = count($image);
for ($i = 0; $i < $counter; $i++) {
$image = Image::make($image[$i]);
$image->resize(null, 627, function ($constraint) {
$constraint->aspectRatio();
});
$image->save(public_path('../../img/testimonial/' . time() . '.png'));
}
}
}
it shows error
Symfony\Component\Debug\Exception\FatalThrowableError
Cannot use object of type Intervention\Image\Image as array
can anyone please help me how can I upload multi file using intervention image package?
Please try the following:
public function addReviewPost(Request $request)
{
if (request()->hasFile('image')) {
$images = $request->file('image');
foreach ($images as $key => $file) {
$image = Image::make($request->file($file));
$image->resize(null, 627, function ($constraint) {
$constraint->aspectRatio();
});
$image->save(public_path('../../img/testimonial/' . time() . '.png'));
}
}
}
Let me know If you get any errors.
Don't forget to mark it answer if works
Hope it helps you
Thank you
html
<input type="file" name="images[]" multiple accept="image/*">
Controller
foreach ($request->images as $key=>$image) {
$iimage = Image::make($image)
->resize(350, 150)
->encode('jpg');
Storage::disk('local')->put('public/gallery_images/' . $image->hashName(), (string)$iimage, 'public');
$request_data['image'] = 'gallery_images/'. $image->hashName();
$request_data['owner_id'] = auth()->guard('owner')->user()->id;
Gallery::create($request_data);
}//end of foreach

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