Intervention image multiple image upload in laravel - php

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

Related

upload multiple images using laravel API : with polymorphic relation

I'm building an API with Laravel 8 and I have posts and images table with polymorphic relation
So I want to upload multiple images and I'm doing it in postman, And when I upload images and enter posts fields with values, like this:
as you can see, I have an error in my foreach($files as $file)
ErrorException: Invalid argument supplied for foreach()
(In headers part Content-Type has multipart/form-data value )
So I think my problem is in store() method in postController ,
The codes :
post tables :
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('category_id');
$table->unsignedBigInteger('user_id');
$table->string('title');
$table->longText('body');
$table->string('video')->nullable();
$table->string('study_time');
$table->integer('likes')->nullable();
$table->tinyInteger('status')->nullable()->comment('status is 1 when a post is active and it is 0 otherwise.')->nullable();
$table->text('tags')->nullable();
$table->foreign('category_id')->references('id')->on('categories');
$table->foreign('user_id')->references('id')->on('users');
});
and my image table :
Schema::create('images', function (Blueprint $table) {
$table->id();
$table->integer('imageable_id');
$table->string('imageable_type');
$table->string('url');
$table->timestamps();
});
and the post model :
.
.
.
.
public function image(){
return $this->morphOne(Image::class , 'imageable');
}
and my image model :
protected $fillable = [
'url'
];
public function imageable(){
return $this->morphTo();
}
and my store() method in postController :
public function store(Request $request )
{
$post = new Post;
$post->category_id = $request->get('category_id');
$post->title = $request->get('title');
$post->body = $request->get('body');
$post->study_time = $request->get('study_time');
$post->tags = $request->get('tags');
$post->user_id = JWTAuth::user()->id;
$tags = explode(",", $request->tags);
$post->tag($tags);
$allowedfileExtension=['pdf','jpg','png'];
$files = $request->file('fileName');
foreach ($files as $file) {
$extension = $file->getClientOriginalExtension();
$check = in_array($extension, $allowedfileExtension);
if($check) {
foreach($request->fileName as $mediaFiles) {
$url = $mediaFiles->store('public/images');
//store image file into directory and db
$image = new Image();
$image->url = $url;
}
}
else {
return response()->json(['invalid_file_format'], 422);
}
}
$post->image()->save($image);
$post->save();
return response()->json($post , 201);
}
thank you for your help :}
$files = $request->file('fileName');
... is returning null in your case, done you are not posting fileName, you use url.
If you would have validated your incoming data you would have received a validation errors 6 because of this. So: always validate incoming d data. Not only to catch errors like this, also b for security reasons.
public function store(Request $request)
{
if ($this->getErrorIfAny($request->all(), $this->ruls)) {
return $this->getErrorIfAny($request->all(), $this->ruls);
}
if (!$request->hasFile('image_url')) {
return response($this->getResponseFail(trans('my_keywords.uploadFileNotFound'), false), 400);
}
$allowedfileExtension = ['jpg', 'png', 'jpeg'];
$files = $request->file('image_url');
$number_photos_upload = count($files);
$pictures_available_upload = array();
for ($i = 0; $i < count($files); $i++) {
$extension = $files[$i]->getClientOriginalExtension();
$check = in_array($extension, $allowedfileExtension);
if ($check) {
$pictures_available_upload[$i] = $files[$i];
}
}
$number_images_success_uploded = 0;
$images_urls = array();
for ($i = 0; $i < count($pictures_available_upload); $i++) {
$image = $pictures_available_upload[$i];
$path = config('paths.storage_path') .
$image->store(config('paths.store_image_path'), 'public');
//store image file into directory and db
$store_images = new StoreImages();
$store_images['store_id'] = $request['store_id'];
$store_images['image_url'] = $path;
$result = $store_images->save();
if ($result) {
$images_urls[$i] = $path;
$number_images_success_uploded = $number_images_success_uploded + 1;
}
}
if ($number_images_success_uploded == 0) {
return response($this->getResponseFail(trans('my_keywords.invalidFileFormat'), false), 422);
} else {
$data = [
'store_id' => (int) $request['store_id'],
'number_photos_upload' => $number_photos_upload,
'number_images_success_uploded' => $number_images_success_uploded,
'images' => $images_urls,
];
return response($this->getResponse(__('my_keywords.operationSuccessfully'), true, $data), 200);
}
}

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

Undefined variable: image_name Laravel 5.4

I want to upload and display image, but i get error
Undefined variable: image_name
This is my controller
$supply = new DataSupplyProcess;
if($request->hasFile('supply_photo')){
$photo = Validator::make($request->all(), [
'supply_photo' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
if($photo->fails()){
return redirect()->back()->with('warning', 'Image size should be 2MB or less');
}
$image = $request->file('supply_photo');
$image_name = rand().'.'. $image->getClientOriginalExtension();
$destination_path = public_path('/item');
$image->move($destination_path, $image_name);
//dd($image);
}
$supply->item = $request->item;
$supply->supply_details = $request->supply_details;
$supply->tgl_request_date = $request->tgl_need_date;
$supply->tgl_need_date = $request->tgl_need_date;
$supply->employee_id = $id;
$supply->id_approved_by = $manager->employee_manager_id;
$supply->is_approved = 0;
$supply->is_final_approved = 0;
$supply->supply_photo = $image_name;
$supply->save();
This Is My View
<label for="supply_photo">Photo</label>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" class="form-control" name="supply_photo">
In your controller, try something like:
if(Input::file('supply_photo') !== null){
$photo = Validator::make($request->all(), [
'supply_photo' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
...
}
I think this post can provide more info
when ever you pass variable like this with IF condition assign default value first.
so you won't get error if image not selected.
and in your cause check first you get image or not
dd($image = $request->file('supply_photo'));
$image_name = NULL;
if($request->hasFile('supply_photo')){
$image = $request->file('supply_photo');
$image_name = rand().'.'. $image->getClientOriginalExtension();
$destination_path = public_path('/item');
$image->move($destination_path, $image_name);
}
$supply->supply_photo = $image_name;
$supply->save();
$supply = new DataSupplyProcess;
if($request->hasFile('supply_photo')){
$photo = Validator::make($request->all(), [
'supply_photo' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
if($photo->fails()){
return redirect()->back()->with('warning', 'Image size should be 2MB or less');
}
//$original_name=$request->file('supply_photo')->getClientOriginalName();
//$size=$request->file('supply_photo')->getSize();
$extension=$request->file('supply_photo')->getClientOriginalExtension();
$filename=uniqid().'.'.$extension;
$imagepath=url('/item/'.$filename);
$path=$request->file('supply_photo')->storeAs(public_path('/item'),$filename);
}

Image is saving as tmp file

I'm trying to save image using Laravel
Image is saved as tmp file in database, why so?
the image saved as C:\xampp\tmp\phpA3EB.tmp in the database
how can I fix this?
in the controller:
public function update(Request $request, Bank $bank)
{
if ( isset($request->photo) && $request->photo ) {
$request['image'] = UploadImage($request->file('photo'), 'bank', '/banks');
#unlink(public_path('/uploads/banks/') . $bank->image);
}
$updated = $bank->update($request->all());
$bank->updateTranslations([
'name' => $request->get('name_en'),
]);
return $updated ?
redirect()->route('banks.index')->with('success', trans('messages.updateTrue')) :
redirect()->back()->with('warning', trans('messages.updateFalse'));
}
function UploadImage($inputRequest, $prefix, $folderNam)
{
$imageName = $prefix.'_'.time().'.'.$inputRequest->getClientOriginalExtension();
$destinationPath = public_path('/uploads/'.$folderNam);
$inputRequest->move($destinationPath, $imageName);
return $imageName ? $imageName : false;
}
please try this :
public function UploadImage($image, $path)
{
$type = $image->getMimeType();
$ext = substr($type, 6, strlen($type) -1 );
$picName = uniqid() . '.' .$ext;
$image->move(public_path($path), $picName);
return $path . '/' . $picName;
}
}
Please try this :
public function UploadImage($image, $prefix, $path)
{
$ext = $image->extension();
$filename = $prefix.'_'.uniqid() . '.' .$ext;
$image->move(public_path('/uploads/'.$path), $filename);
return $filename;
}
I too struggled with mine for quite a while. However, I realized that I was doing everything okay but how I saved/created it on my database was the problem.
Here is what worked.
public function store(Request $request)
{
$request->validate([
'title'=>'required',
'features'=>'required',
'website'=>'required',
'img'=>'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$input=$request->all();
$imagePath=$request->file('img');
$imageName=time().'.'.$imagePath->getClientOriginalExtension();
$imagePath->move('uploads',$imageName);
$input['img']=$imageName;
Portfolio::create($input);
return Redirect::to('portfolio')->with('success','Great! Portfolio item created successfully.');
}

Only update image if user uploaded a new one, Laravel

I have an edit form which has an image field where a user can upload a new image if he wants to.
But if the user does not upload a new photo I don't want to validate the image field and just use the photo that's already in the database. And not update the image field at all.
Here is my edit function:
public function postEdit($id) {
$product = Product::find($id);
// This should be in product model, just testing here
$edit_rules = array(
'category_id' => 'required|integer',
'title' => 'required|min:2',
'description' => 'required|min:10',
'price' => 'required|numeric',
'stock' => 'integer'
);
// Add image rule only if user uploaded new image
if (Input::has('image')) {
$edit_rules['image'] = 'required|image|mimes:jpeg,jpg,bmp,png,gif';
}
$v = Validator::make(Input::all(), $edit_rules);
if ($product) {
if ($v->fails()) {
return Redirect::back()->withErrors($v);
}
// Upload the new image
if (Input::has('image')) {
// Delete old image
File::delete('public/'.$product->image);
// Image edit
$image = Input::file('image');
$filename = date('Y-m-d-H:i:s')."-".$image->getClientOriginalName();
Image::make($image->getRealPath())->resize(600, 600)->save('public/img/products/'.$filename);
$product->image = 'img/products/'.$filename;
$product->save();
}
// Except image because already called save if image was present, above
$product->update(Input::except('image'));
return Redirect::to('admin/products')->with('message', 'Product updated.');
}
return Redirect::to('admin/products');
}
Using this I can update all the values except the image.
If I don't upload a new photo it saves all other updated values.
If I do upload a new photo it just ignores it and saves all other updated values, doesn't upload the new photo.
Check if the request has the file:
public function update(Request $request)
{
// Update the model.
if($request->hasFile('photo')) {
// Process the new image.
}
// ...
}
public function update() {
$id=Input::get('id');
$rules= array('name'=>'required|regex:/(^[A-Za-z]+$)+/',
'detail'=>'required|regex:/(^[A-Za-z]+$)+/',
'images' => 'required|image');
$dat = Input::all();
$validation = Validator::make($dat,$rules);
if ($validation->passes()){
$file =Input::file('images');
$destinationPath = 'image/pack';
$image = value(function() use ($file){
$filename = date('Y-m-d-H:i:s') . '.' . $file->getClientOriginalExtension();
return strtolower($filename);
});
$newupload =Input::file('images')->move($destinationPath, $image);
DB::table('pkgdetail')
->where('id', $id)
->limit(1)
->update(array('name' => Input::get('name'), 'detail' => Input::get('detail'), 'image' => $newupload));
$data=PackModel::get_all();
return View::make('pkg_dis')->with('data',$data)
->withErrors($validation)
->with('message', 'Successfully updated.');
}
}
use Illuminate\Support\Facades\Input;
public function update(Request $request, $id)
{
if ($tag = Tag::find($id))
{
$this->validate($request, [
'tag_name' => 'required|min:3|max:100|regex: /^[a-zA-Z0-9\s][a-zA-Z0-9\s?]+$/u|unique:tags,tag_name,'.$id.',id',
]);
$tag->tag_name=$request->input('tag_name');
// get the image tag_img_Val
if($request->hasFile('tag_image'))
{
$this->validate($request, [
'tag_image' => 'image|mimes:jpeg,png,jpg,gif,svg|max:1000',
]);
$img = $request->file('tag_image');
$old_image = 'uploads/' . $tag->tag_image;//get old image from storage
if ($img != '')
{
$image = rand() . '_' . ($img->getClientOriginalName());
$path = 'uploads/';
//Storing image
if ($img->move(public_path($path), $image))
{
$tag->tag_image = $image;
if ($tag->update())
{
if (is_file($old_image)) {
unlink($old_image); // delete the old image
}
return response()->json(['message' => 'Tag has been updated successfully.'],200);
}
else
{
unlink($image); // delete the uploaded image if not updated in database
return response()->json(['message' => "Sorry, Tag not updated"],500);
}
}
else
{
return response()->json(['message' => "Sorry, Image not moved"],500);
}
}
else
{
return response()->json(['message' => "Sorry, Image not uploaded"],500);
}
}
else
{
if($tag->update(Input::except('tag_image')))
{
return response()->json(['message' => 'Tag has been updated successfully.'],200);
}
else
{
return response()->json(['message' => "Sorry, Tag not updated"],500);
}
}
}
else
{
return response()->json(['message' => 'Tag not found'], 404);
}
}
You need to use multipart for form enctype
You can use another function to delete the images from the folder. like here
private function unlinkPostImages($images)
{
if(!empty($images)){
foreach ($images as $img){
$old_image = public_path('storage/' . $img->image);
if (file_exists($old_image)) {
#unlink($old_image);
}
}
}
}
Then call this function above image delete function. like this...
$this->unlinkPostImages($getId->images); // this will delete image from folder
$getId->images()->delete(); // --> this delete from database table $post->id
same this Click here..
my update function
public function update(UpdatePostRequest $request, Post $post)
{
//
$data = $request->only(['title', 'description', 'contents', 'price']);
// صورة الإعلان //
if ($request->hasFile('image')) {
Storage::disk('public')->delete($post->image);
$imagePath = $request->image;
$filename = Str::random(10).'-'.time().'-'.$imagePath->getClientOriginalName();
$image_resize = Image::make($imagePath->getRealPath());
$image_resize->fit(120);
$image_resize->orientate();
$image_resize->save(public_path('storage/images/' .$filename), 100);
$sImg = 'images/'. $filename;
$data['image'] = $sImg;
}
// -------- //
if ($request->hasFile('images'))
{
$getId = Post::find($post->id);
$this->unlinkPostImages($getId->images);
$getId->images()->delete();
$uploadPicture = array();
foreach ($request->file('images') as $photo) {
$file = $photo;
$filename = $file->getClientOriginalName();
$picture = date('His').'-'.$filename;
$file->move(public_path('storage/images/'), $picture);
array_push($uploadPicture, new PostImages(array('image' => 'images/'. $picture)));
}
$post->images()->saveMany($uploadPicture);
}
if ($request->input('contents')) {
$data['content'] = $request->contents;
}
//dd($data);
$post->update($data);
session()->flash('SUCCESS', 'تم تحديث الإعلان بنجاح.');
return redirect()->route('post.show', [$post->id, Post::slug($post->title)]);
}
In controller part:
$destinationPath = 'uploads';
$extension = Input::file('image')->getClientOriginalExtension();
var_dump($extension);
$fileName = rand(11111,99999).'.'.$extension;
Input::file('image')->move($destinationPath, $fileName);

Categories