I'm working on a form where you have to enter all information you need and at the end, on save all information will be saved at the same times. The form have a list of images where you can add, change and delete pictures.
The way it was made is that all inputs refer to the name carousels[]. Adding the file is alright, the problem is that this way I have no way to identify in backend which file I have to delete or change.
I'm wondering if any Laravel master know a better way to handle a list of files over a form the way a need it to work. So I would be able to add new images, replace an old image by a new one and/or delete a specific image.
There are the pieces of code I'm working with.
Frontend:
#php
$carrousel = $Ids = [];
foreach ($offerImages as $index => $image) {
$carrousel[] = $image['image'];
$ids[] = $index;
}
#endphp
#for($i = 0; $i < 4; $i++)
<div class="col-sm-4 error-block">
<div class="{{ (!empty($carrousel[$i])) ? 'fileinput fileinput-exists':'fileinput fileinput-new' }}" data-provides="fileinput">
<div class="fileinput-preview thumbnail" id="banner{{$i}}" data-trigger="fileinput">
<img src="{{ !empty($carrousel[$i]) ? asset($carrousel[$i]) : (url('/') . "/images/default-thumbnail.png") }}"></div>
<div>
<span class="btn btn-secondary btn-sm btn-file">
<span class="fileinput-new ">Select image</span>
<span class="fileinput-exists">Change</span>
<input type="file" name="carrousels[]" id="carrousel{{$i}}">
</span>
Remove
</div>
</div>
</div>
#endfor
Backend
public function update(UpdateRequest $request)
{
try {
$id = $request->id;
$carrouselFolder = config('constants.DEFAULT.UPLOAD_FOLDERS.CARROUSEL');
$carrousels = [];
Log::debug($request->carrousels);
if ($request->carrousels) {
foreach ($request->carrousels as $image) {
if (!empty($image)) {
//upload image
$imageName = generateRandomString(30) . '.' . $image->getClientOriginalExtension();
if ($image->move(public_path($carrouselFolder), $imageName)) {
$image = $carrouselFolder . $imageName;
}
$carrousels[] = $image;
}
}
}
return redirect()->to(route('...'))
->with('toastSuccess', '...');
} catch (\Exception $e) {
return redirect()->back()->with('toastError', $e->getMessage());
}
}
send another parameter with old carousel, retrive it in controller then if both not empty, delete the old image . you can try this
View code
#php
$carrousel = $Ids = [];
foreach ($offerImages as $index => $image) {
$carrousel[] = $image['image'];
$ids[] = $index;
}
#endphp
#for($i = 0; $i < 4; $i++)
<div class="col-sm-4 error-block">
<div class="{{ (!empty($carrousel[$i])) ? 'fileinput fileinput-exists':'fileinput fileinput-new' }}" data-provides="fileinput">
<div class="fileinput-preview thumbnail" id="banner{{$i}}" data-trigger="fileinput">
<img src="{{ !empty($carrousel[$i]) ? asset($carrousel[$i]) : (url('/') . "/images/default-thumbnail.png") }}"></div>
<div>
<span class="btn btn-secondary btn-sm btn-file">
<span class="fileinput-new ">Select image</span>
<span class="fileinput-exists">Change</span>
<input type="text" name="oldcarrousels[{{$i}}]" value="{{ !empty($carrousel[$i]) ?$carrousel[$i] :'' }}">
<input type="file" name="carrousels[{{$i}}]" id="carrousel{{$i}}">
</span>
Remove
</div>
</div>
</div>
#endfor
Controller code
foreach ($request->carrousels as $in=>$image) {
if (!empty($image)) {
if (!empty($request->oldcarrousels[$in]) || $request->oldcarrousels[$in]!='') {
//image deleting code here
}
//upload image
$imageName = generateRandomString(30) . '.' . $image->getClientOriginalExtension();
if ($image->move(public_path($carrouselFolder), $imageName)) {
$image = $carrouselFolder . $imageName;
}
$carrousels[] = $image;
}
}
Related
I inserted the image in my database, now I am trying to edit the images and the edited image should be deleted from my folder and a new image should be updated there. Could you please help me where I am mistaking?
Here is my Controller.php file
public function edit($slider)
{
$property=Property::all();
$slider = Slider::find($slider);
$data = ['property'=>$property, 'slider'=>$slider];
return view('admin.slider.edit', $data);
}
public function update(Request $r, $id)
{
$slider=Slider::find($id);
if( $r->hasFile('slider_thumb')){
$thums = $r->slider_thumb;
$slider_thumb = uniqid($chr).'.'.$thums->getClientOriginalExtension();
$img = Image::make($thums->getRealPath());
$img->resize(204, 107, function ($constraint) {
$constraint->aspectRatio();
});
$thumbPath = public_path().'/slider_img/'.$slider_thumb;
if (file_exists($thumbPath)) {
$this->removeImage($thumbPath);
}
$img->save($thumbPath);
$optimizerChain = OptimizerChainFactory::create();
$optimizerChain->optimize($thumbPath);
$slider_thumbimg = $slider_thumb;
}else{
$slider_thumb = NULL;
}
$slider->property_id = $r->property_id;
$slider->slider_image=$slider_imageimg;
$slider->save();
return redirect('/admin/slider');
}
}
here is my HTML file
<form class="form-horizontal" method="POST" action="{{ route('slider.update',['id'=>$slider->id]) }}" enctype="multipart/form-data">
#csrf
#method('PUT')
#if($slider->slider_image == NULL or $slider->slider_image == '')
<img src="{{asset('images/no-image-found.jpg')}}" style="width: 100px; height: 100px;">
#else
<img src="{{ asset('slider_img/'.$slider->slider_image) }}" style="width: 100px; height: 80px;">
#endif
<input type="file" name="slider_image" value="{{ $slider->slider_image }}">
<div class="form-group">
<div class="col-sm-12 text-right">
<button type="submit" class="btn btn-info">
<i class="fa fa-check"></i> Save
</button>
</div>
</div>
</form>
You did not use Laravel standards. you need to refer to laravel filesystem document to upload file. then you need to check request file exist. if request has new file; you should remove old file and upload new file. in else you should not remove old file.
follow below code:
public function store(PostRequest $request,string $slug = null)
{
$postData = $request->all();
//upload and set thumbnail of post, if exist
if($request->file("thumbnail")){
$image = new Images();
$thumbnailName = $image->uploadFile($request,"thumbnail",config("upload_image_path.post-thumbnail"));
$postData["thumbnail"] = $thumbnailName;
}
$post = $this->postService->save($postData,$slug);
Image is not displaying however it is saving in db and folder.
I could not get it where is the problem
apperance.blade.php
<div id="bgimage" class="hovercover text-center">
<img class="img-responsive" src="img/{{$image->image ?? ''}}" style="margin-top: {{$image->position ?? ''}}">
<div class="hover-div">
<form id="hoverform" action="{{url('/employee-appearance')}}" enctype="multipart/form-data" method="post">
{{ csrf_field() }}
<label class="custom-file-upload" title="Change Cover Image" for="file-upload"> <i class="fa fa-file-image-o"></i> Change Cover </label>
<input id="file-upload" name="file" type="file">
</form>
</div>
</div>
<div id="adjimage" class="hovercover1 text-center" style="display: none;">
</div>
imageProcessController
public function upload()
{
$image=DB::table('images')->latest('image','position')->first();
return view('user.employeeforms.appearance',compact('image')) ;
}
public function postupload(Request $request)
{
$file = $request->file('file');
$rules = array('file' => 'required|mimes:png,gif,jpeg,jpg');
$validator = Validator::make(array('file'=> $file), $rules);
if($validator->passes()) {
$image = $file->move( 'img', sprintf('%s-%s.%s', time(), "abc", explode('/', $file->getMimeType())[1]));
$img = new Image;
$img->image = $image->getFilename();
$img->save();
}
}
There may be possibilities that it could be.
But the most likely one is that the symlink has not been set yet!?
php artisan storage:link
If you have already set it, look in the storage/app order where the files are. If they are under storage/app/img then you have to change the link like this:
<img src="img/{{$image->image ?? ''}}"
should be:
<img src="{{ asset('storage/img/' . $image->image ?? "placeholder.jpg" ) }}">
I was successful uploading multiple images while inserting a new record. I used two models Car and caralbum and made a join. However, I was trying to create an option to add more images on current list but failed to do so. my codes are-
controller to add new record with multiple images
$car = new Car;
.......
.......
$car->save();
if (count($request->car_image) > 0) {
foreach ($request->car_image as $image) {
........
........
Image::make($image)->save($location);
$caralbum = new caralbum;
$caralbum->car_id = $car->id;
$caralbum->image_name = $image_name;
$caralbum->image_location = $location;
$caralbum->save();
}
}
controller to add additional images
$car = Car::find($id);
if (count($request->car_image) > 0) {
foreach ($request->car_image as $image) {
....
....
Image::make($image)->save($location);
$caralbum = new caralbum;
$caralbum->car_id = $car->id;
$caralbum->image_name = $image_name;
$caralbum->image_location = $location;
$caralbum->save();
blade to add new record with multiple images
<input type="file" name="car_image[]" multiple>
blade to add additional images
<input type="file" name="car_image[]" multiple>
<a class="btn btn-success" href="{{ url('car_store_images/'.$cars->id) }}">
Add Images
</a>
I have found one problem. on the index blade where I am displaying the images the image class was not named as array. After adding [] after it, it is working now.
#foreach ($cars->join_caralbum as $image)
<div class="card" >
<img class="card-img-top" name="car_image[]" src="{{asset($image->image_location)}}" style ="height:90px; width:120px;" >
<a class="btn btn-danger" href="{{ url('car_destroy_image/'.$image->id) }}"
onclick="return confirm('Are you sure you want to delete all images for this car?')"><i class="fas fa-trash fa-xs"></i></a>
</div>
#endforeach
In my laravel project, I have uploaded the image in database and it shows image in view file properly.
Now I want to get the image dimension, So How can I get this?
Can anyone help me plz?
This is my controller for uploading image.
public function store(Request $request)
{
request()->validate([
'image' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
// if ($request->hasFile('image')) {
// $image = $request->file('image');
// $extension = $image->getClientOriginalExtension();
// $filename = time() . "." . $extension;
// $image->move('public/mediaLibrary', $filename);
// }
$image = $request->file('image');
$extension = $image->getClientOriginalExtension();//Getting extension
$originalname = $image->getClientOriginalName();//Getting original name
//this code will store image in laravel default storage folder $path = $image->storeAs('', $originalname);
$path = $image->move('uploads/media/', $originalname);//This will store in customize folder
$imgsizes = $path->getSize();
$mimetype = $image->getClientMimeType();//Get MIME type
//Start Store in Database
$picture = new mediaLibrary();
$picture->mime = $mimetype;
$picture->imgsize = $imgsizes;
$picture->original_filename = $originalname;
$picture->extension = $extension;
$picture->filename = $path;
$picture->save();
//End Store
return redirect()->route('media.index');
}
This is my blade file code where i want to show
<div class="card-body" >
<span><i class="fa fa-calendar" aria-hidden="true"></i> Uploaded on:</span>
<strong><p class="text-muted" style="display: inline">
{{ date('F d, Y',strtotime($data->created_at)) }} at {{ date('g : ia',strtotime($data->created_at)) }}
</p></strong>
<hr>
<span>File Name:</span>
<strong><p style="display: inline;">{{$data->original_filename}}</p></strong>
<hr>
<span>File type:</span>
<strong><p style="display: inline;">{{$data->extension}}</p></strong>
<hr>
<span>Fle Size:</span>
<strong><p style="display: inline;"></p>{{round(($data->imgsize)/1024 )}}KB</strong>
{{-- <strong><p style="display: inline;"></p>{{(File::size($data->filename))/1024}} KB</strong> --}}
<hr>
<span>Dimension:</span>
<strong><p style="display: inline;">
</p></strong>
</div>
You may use getimagesize() native PHP method
list($width, $height) = getimagesize('path_to_image');
Or via
Intervention Image package
// read width of image
$width = Image::make('public/foo.jpg')->width();
// read height of image
$height = Image::make('public/foo.jpg')->height();
Controller Image Store function
public function store(Request $request)
{
request()->validate([
'image' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$image = $request->file('image');
$extension = $image->getClientOriginalExtension();//Getting extension
$originalname = $image->getClientOriginalName();//Getting original name
$path = $image->move('uploads/media/', $originalname);//This will store in customize folder
$imgsizes = $path->getSize();
$data = getimagesize($path);
$width = $data[0];
$height = $data[1];
$mimetype = $image->getClientMimeType();//Get MIME type
//Start Store in Database
$picture = new mediaLibrary();
$picture->mime = $mimetype;
$picture->imgsize = $imgsizes;
$picture->original_filename = $originalname;
$picture->extension = $extension;
$picture->width = $width;
$picture->height = $height;
$picture->filename = $path;
$picture->save();
//End Store
return redirect()->route('media.index');
}
And view the file
<div class="card-body" >
<span><i class="fa fa-calendar" aria-hidden="true"></i> Uploaded on:</span>
<strong><p class="text-muted" style="display: inline">
{{ date('F d, Y',strtotime($data->created_at)) }} at {{ date('g : ia',strtotime($data->created_at)) }}
</p></strong>
<hr>
<span>File Name:</span>
<strong><p style="display: inline;">{{$data->original_filename}}</p></strong>
<hr>
<span>File type:</span>
<strong><p style="display: inline;">{{$data->extension}}</p></strong>
<hr>
<span>Fle Size:</span>
<strong><p style="display: inline;"></p>{{round(($data->imgsize)/1024 )}}KB</strong>
{{-- <strong><p style="display: inline;"></p>{{(File::size($data->filename))/1024}} KB</strong> --}}
<hr>
<span>Dimension:</span>
<strong><p style="display: inline;">
{{$data->width}} <i class="fa fa-times" aria-hidden="true"></i> {{$data->height}}
</p></strong>
<hr>
<span>File URL:</span>
<input type="text" class="mediaLib" name="image_url" value="{{url('uploads/media',$data->original_filename)}}" readonly="" style="
display: block;
background-color: #eee;
padding: 0 8px;
line-height: 2;
border-radius: 4px;
border: 1px solid #7e8993;
color: #32373c;
border-spacing: 0;
width:-webkit-fill-available;">
</div>
Note this is the database table fields:
https://imgur.com/O1w8ocT
M working on a solution where by i need to pass data from controller to view, Based on the id.
I've tested each variable one by one for see if there is actual data contained in those variables.
one-by-one produces all the values required and as soon as i comment out the var_dumps(). Throws an Undefined index error.
Please See code below:
View
<td>
<a href="view-campaign/{{$item->id}}" class="btn btn-success mb-2"
data-toggle="tooltip" title="view campaign">
<i class="fa fa-eye"></i>
</a>
</td>
Controller
public function viewCampaign($id){
//return var_dump($id);
$img = null;
//firebase configs and send to firebase
$serviceAccount = ServiceAccount::fromJsonFile(__DIR__.'/serviceKey.json');
$firebase = (new Factory)
->withServiceAccount($serviceAccount)
->withDatabaseUri('https://projectName.firebaseio.com/')
->create();
$database = $firebase->getDatabase();
$ref = $database->getReference('CampaignCollection')->getValue();
foreach($ref as $key){
$item = $key['id'];
//return var_dump($item);
$poster = $key['Poster'];
//return var_dump($poster);
if($item = $id){
//return '1';
$img = $poster;
//return var_dump($poster);
}else{
return '0';
}
}
return view('view-campaign')->with('img',$img);
}
Route
Route::get('view-campaign/{id}','CampaignController#viewCampaign');
View::Results
#extends('layouts.layout')
#section('content')
<div class="col-md-12">
<div class="col-md-12 panel">
<div class="col-md-12 panel-heading">
<h4>View Campaign:</h4>
</div>
<div id="imgContainer" class="col-md-12 panel-body">
<i class="fa fa-arrow-circle-left"></i>
#if(isset($img))
<div align="center">
<img src="{{($img)}}" />
</div>
#else
no data
#endif
</div>
</div>
</div>
#endsection
Goal is to get the base64 code to pass to the view.
Try replacing your foreach with the following code:
foreach($ref as $k1 => $key){
$item = $key->id; //change over here
//return var_dump($item);
$poster = $key->Poster; //change over here
//return var_dump($poster);
if($item == $id){ //change over here
//return '1';
$img = $poster;
//return var_dump($poster);
}else{
return '0';
}
}
I reckon, you would also have to update the function signature to look something like following:
public function viewCampaign(Request $request , $id){
//your code
}