Laravel upload multiple files - laravel

I'm building a gallery with multiple files functionality.
So far I'm having two issues, but let's paste my code first.
Controller:
public function store(Request $request)
{
$gallery = new GalleryImage();
if($request->hasFile('image')) {
$images = $request->file('image');
foreach($images as $image) {
$path = $image->getClientOriginalName();
$name = time() . '-' . $path;
$gallery->image = $image->move(public_path().'/uploads/temp/', $name);
//$gallery->image = $request->file('image')->storeAs('public/gallery-images', $name);
}
}
$gallery->gallery_id = $request->gallery_id;
$gallery->save();
return back()->with('success_message','Images has been uploaded!');
}
View blade:
<form action="{{ route('gallery-images.store') }}" method="POST" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="form-group">
<input type="hidden" name="gallery_id" value="{{ $gallery->id }}">
<input type="file" name="image[]" id="id_imageGallery" class="form-control" multiple="multiple" required>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Upload</button>
</div>
</form>
My first issue when I have my code like this and upload three files, it's successfully storing the files into /uploads/temp directory, but in my database I can see there's only one image uploaded, instead of three.
My second issue is when I change my code and use the commented part (because I want to store those three images into Storage):
$gallery->image = $request->file('image')->storeAs('public/gallery-images', $name);
I'm getting this error:
Call to a member function storeAs() on array
How can I upload those multiple images into the Storage folder and record them all into the database?
-- EDIT --
I've solved my first issue!
I've simply put the save method and other details inside the loop. I've should have thought about this before :)
Here's my updated code:
public function store(Request $request)
{
if($request->hasFile('image')) {
$images = $request->file('image');
foreach($images as $image) {
$gallery = new GalleryImage();
$path = $image->getClientOriginalName();
$name = time() . '-' . $path;
$gallery->image = $image->move(public_path().'/uploads/temp/', $name);
//$gallery->image = $request->file('image')->storeAs('public/gallery-images', $name);
$gallery->gallery_id = $request->gallery_id;
$gallery->save();
}
}
return back()->with('success_message','Images has been uploaded!');
}
Now only thing to do is how to store them into File Storage, instead of the public_path and avoid that error:
Call to a member function storeAs() on array

I've finally solved the issues and I'm posting it, so it may be useful for some.
Here's my code:
public function store(Request $request)
{
if($request->hasFile('image')) {
foreach($request->image as $image) {
$path = $image->getClientOriginalName();
$name = time() . '-' . $path;
$gallery = new GalleryImage();
$gallery->image = $image->storeAs('public/gallery-images', $name);
$gallery->gallery_id = $request->gallery_id;
$gallery->save();
}
}
return back()->with('success_message','The images have been uploaded!');
}

Try to implement using the following code, it will give uploaded files url in serialized format
public static function upload_file($file){
$file_name = time();
$file_name .= rand();
$file_name = sha1($file_name);
if ($file) {
$ext = $file->getClientOriginalExtension();
$file->move(public_path() . "/uploads", $file_name . "." . $ext);
$local_url = $file_name . "." . $ext;
$s3_url = url('/').'/uploads/'.$local_url;
return $s3_url;
}
return "";
}
public static function upload_multiple_files($files){
if(is_array($files)){
$return_array = array();
foreach ($files as $file){
if(!empty($file)){
$return_array[] = self::upload_file($file);
}else{
$return_array[] = '';
}
}
return serialize($return_array);
}else{
return NULL;
}
}

//I have updated and commented your code. Try it, It should work.
public function store(Request $request)
{
if($request->hasFile('image')) {
$images = $request->file('image');
foreach($images as $image) {
$gallery = new GalleryImage();
// laravel auto manages unique name and extension of file.
$gallery->image = $image->store('gallery-images', 'public');
$gallery->gallery_id = $request->gallery_id;
$gallery->save();
}
}
return back()->with('success_message','Images has been uploaded!');
}

Related

Image does not displayed - How to display an image perhaps dynamically

I would like to display an employee picture using the url as shown below which I think should work but not. However it does work with the second url which is static. why is this happening?
This the first url that does not work
<img id="message" src="{{url('/profile_picture/' . $employee->picture)}}" style="width: 150px;"/>
This is the second url that does work
<img id="message" src="{{url('/profile_picture/20220615232745.jpg')}}" style="width: 150px;"/>
To save a picture I use the following method
public function ProfileStore(Request $request)
{
$data = User::find(Auth::user()->id);
$data->name =$request->name;
$data->email =$request->email;
if ($request->file('picture')) {
$file = $request->file('picture');
$filename = date('YmdHis') . "." . $file->getClientOriginalExtension();
$file->move('profile_picture/', $filename);
$data['picture'] = " $filename";
}
$data->save();
return redirect()->route('profile.index');
}
The route
Route::post('/people/employees/profiles/store', [ProfileController::class, 'ProfileStore'])->name('profile.store');
Route::get('/people/employees/profiles/edit/{id}', [ProfileController::class, 'ProfileEdit'])->name('profile.edit');
My edit method
public function ProfileEdit()
{
$id = Auth::user()->id;
$employee = User::find($id);
return view('fms.people.employee.profiles.profile_edit')->with('employee',$employee);
}
in you profilestore function, when setting the $filename to $data['picture'], you have extra space before it.Remove that space and try again. For ex:
if ($request->file('picture')) {
$file = $request->file('picture');
$filename = date('YmdHis') . "." . $file->getClientOriginalExtension();
$file->move('profile_picture/', $filename);
$data['picture'] = "$filename";
}

How to convert base64 images to Url images when using summer note text editor in Laravel inside controller?

I am trying to use image url instead of base64. i kindof figured a way how to get images out of the editor and save it inside the directory, but i am trying to insert it into database. i get this error.
Object of class DOMElement could not be converted to string
below i have added the store function inside my controller
public function store(Request $request)
{
//
$data = $request->all();
if (!$request->has('published')) {
$data['published'] = 0;
} else {
$data['published'] = 1;
}
if (!$request->has('featured')) {
$data['featured'] = 0;
} else {
$data['featured'] = 1;
}
$img = null;
if ($request->hasfile('title_img')) {
$image = $request->file('title_img');
$name = time() . '.' . $image->getClientOriginalExtension();
$image->move(public_path() . '/uploads/blogs/', $name);
$img = '/uploads/blogs/' . $name;
}
/* summernote */
$detail=$data['description'];
$dom = new \DomDocument();
$dom->loadHtml($detail, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$images = $dom->getElementsByTagName('img');
foreach($images as $k => $img){
$data = $img->getAttribute('src');
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
$image_name= "/uploads/summernote/" . time().$k.'.jpeg';
$path = public_path() . $image_name;
file_put_contents($path, $data);
$img->removeAttribute('src');
$img->setAttribute('src', $image_name);
}
$detail = $dom->saveHTML();
/* summernote */
$data['title_img'] = $img;
$data['user_id'] = auth()->user()->id;
$title = $data['title'];
$data['slug'] = Str::slug($title);
auth()->user()->posts()->create($data);
return Redirect::route('admin.blog.index')->withSuccess('Whoopie!! New Blog Added!');
}
I hope i can get some help regarding this. Thanks in advance

How to update a product in Laravel 5.8

I have a product that I want to edit. Please see the following code.
public function update(ProductRequest $request, Product $product)
{
$product->user_id = auth()->user()->id;
$product->title = $request->title;
$product->body = $request->body;
$product->price = $request->price;
if ($request->has('image')) {
$image = $request->file('image');
$filename = $image->getClientOriginalName();
$image->move(public_path('images/products'), $filename);
$product->image = $request->file('image')->getClientOriginalName();
}
$product->update();
$product->categories()->sync($request->category);
return redirect()->route('products.index');
}
product.blade.php
<form class="form-horizontal" action="{{ route('products.update', $product->id) }}" method="post" enctype="multipart/form-data">
{{ csrf_field() }}
{{ method_field('PATCH') }}
.
.
.
Everything changes except the image. I tried it, but, I did not succeed. What's the solution? I want to update the image in the database.
OK, I go to database now, I changed in image to picture, then I go my project, and I tested this again.
But it did not event for me.
I changed
public function update(ProductRequest $request, Product $product)
To
public function update(Request $request, Product $product)
To update a model, you should retrieve it, set any attributes you wish to update, and then call the save method. See the updates section in the documentation.
public function update(ProductRequest $request, Product $product)
{
$product->user_id = auth()->user()->id;
$product->title = $request->title;
$product->body = $request->body;
$product->price = $request->price;
if ($request->has('image')) {
$image = $request->file('image');
$filename = $image->getClientOriginalName();
$image->move(public_path('images/products'), $filename);
$product->image = $request->file('image')->getClientOriginalName();
}
$product->save();
$product->categories()->sync($request->category);
return redirect()->route('products.index');
}
Update 1
Assuming you have debugged the above and $request->file('image')->getClientOriginalName() is returning the expected value, it's possible that you are using field whitelisting on your model and haven't added the image field to the whitelist. Make sure that image is in the $fillable array on your model.
class Product extends Model
{
protected $fillable = [
'user_id',
'title',
'body',
'price',
...
'image'
];
Update 2
If $request->file('image') is returning null then that would suggest your form is not submitting the files. Ensure your <form> element has the enctype="multipart/form-data" attribute included in the tag.
Update 3
If your already including the required enctype="multipart/form-data" tags in the <form> element then I would suggest doing the following.
Place dd($request->all()); at the top of your update(ProductRequest $request, Product $product) method. Post the form and check the output.
If the file is not included in the output, change from using ProductRequest $request to the default Request $request (Illuminate\Http\Request) and try it again. There could be something in your ProductRequest class that is causing a problem.
As a small critique, you could improve your code in the following ways.
・Use hasFile() instead of has().
・Use $product-image = $filename instead of $product->image = $request->file('image')->getClientOriginalName();.
public function update(ProductRequest $request, Product $product)
{
$product->user_id = auth()->user()->id;
$product->title = $request->title;
$product->body = $request->body;
$product->price = $request->price;
if ($request->hasFile('image')) {
$image = $request->file('image');
$filename = $image->getClientOriginalName();
$image->move(public_path('images/products'), $filename);
$product->image = $filename;
}
$product->save();
$product->categories()->sync($request->category);
return redirect()->route('products.index');
}
make sure your has
enctype="multipart/form-data"
property

Multi image uploader using CodeIgniter

I am a new user to using code igniter in my project, I am facing one problem while uploading multiple files but only function image uploading images and save into the database and function sliderimage is not uploading images or save into the database?
Controller
public function manage($id = FALSE) {
$data = array();
if ($id) {
$this->{$this->model}->{$this->_primary_key} = $id;
$data['item'] = $this->{$this->model}->get();
if (!$data['item'])
show_404();
} else {
$data['item'] = new Std();
}
$this->load->library("form_validation");
$this->form_validation->set_rules("image", 'Image', "trim|callback_image[$id]");
$this->form_validation->set_rules("sliderimage", 'sliderimage', "trim|callback_image[$id]");
if ($this->form_validation->run() == FALSE)
$this->load->view($this->module . '/manage', $data);
else {
$this->{$this->model}->save();
redirect('admin/' . $this->module);
}
}
public function image($var, $id) {
$config['upload_path'] = './cdn/sliders/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$this->load->library('upload', $config);
if ($this->upload->do_upload('image')) {
$data = $this->upload->data();
if ($data['file_name'])
$this->{$this->model}->image = base_url() . '/cdn/sliders/' . $data['file_name'];
}
return true;
}
public function sliderimage($var, $id) {
$config['upload_path'] = './cdn/sliders/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$this->load->library('upload', $config);
if ($this->upload->do_upload('sliderimage')) {
$data = $this->upload->data();
if ($data['file_name'])
$this->{$this->model}->sliderimage = base_url() . '/cdn/sliders/' . $data['file_name'];
}
return true;
}
Html Form
<form role="form" class="form-horizontal" role="form"
method="post" enctype="multipart/form-data">
<input class="form-control" type="file" name="image" >
<input class="form-control" type="file" name="sliderimage">
</form>
insted of calling both time image function call:
$this->form_validation->set_rules("sliderimage", 'sliderimage', "trim|callback_sliderimage[$id]");

How to Upload an Image in Laravel 5

I am new to Laravel 5. Actually I'm using Laravel Framework version 5.1.16. When uploading an image, it is uploading and saved in database table, but it is not moved to a specified folder.
Any help would be appreciated.
This is my controller code:
public function addexpense(Request $request) {
$inputs=Input::all();
$validation = Validator::make($inputs, Expense::$rules);
if($validation->fails()) {
return Redirect::to('expenseaddform')->withErrors($validation)->withInput();
}else{
$input=Input::only('id','expense_date','expense_category_id','vendor_id','customer_id','amount','tax1_id','tax2_id','note','receipt');
$data->expense_date = $input['expense_date'];
$data->expense_category_id = $input['expense_category_id'];
$data->vendor_id = $input['vendor_id'];
$data->customer_id = $input['customer_id'];
$data->amount = $input['amount'];
$data->tax1_id = $input['tax1_id'];
$data->tax2_id = $input['tax2_id'];
$data->note = $input['note'];
$image = Input::file('receipt');
$filename = date('Y-m-d-H:i:s')."-".$image->getClientOriginalName();
Image::make($image->getRealPath())->resize(468, 249)->save('public/uploas/'. $filename);
$data->receipt = $input['image'];
$data->save();
return redirect('expenseinfo');
}
}
Form code:
<form action="addexpense" enctype="multipart/form-data" >
Receipt:</td><td><input type="file" name="receipt"value="{{Input::old('receipt')}}">
<input style="margin-left:30px"type="submit" value="Add" name="submit">
</form>
You are doing it wrong with Image::make() function. Try the following:
Image::make($image->getRealPath())->resize(468, 249)->save(public_path() . '/uploads/' . $filename);
Try this:
Image::make($image->getRealPath())->resize(468, 249)->save(public_path('uploads/'). $filename);
For more information you can check the below link:
https://youtu.be/F92JpVWhDw4

Resources