Laravel - Upload Image 404 - php

I want to display an image on my website that i uploaded.
In my database the image is store in local/temp/ i don't know why.
I'm getting a 404 not found error when I want to access to the image
http://projet-site-e-commerceb2.test/storage/uploads/cL9pMFrZO92vliCKvlSgCq64TZOvnG3C2uzxgl6r.jpeg
I did php artisan storage:link to put the storage folder to remain public.
After i uploaded an image, i can see it in public/storage/uploads
HTML
<img src="{{ asset('/storage/' . $product->image)}}" style="height:200" class="card-img-top">
ProdcuctControllerController
public function store(Request $request)
{
$inputs = $request->except('_token');
$product = new Product();
$this->storeImage($product);
foreach ($inputs as $key => $value) {
$product->$key = $value;
}
$product->save();
return redirect('admin/gamelist');
}
public function storeImage($product)
{
if (request()->has('image')){
$product->update([
'image' => request()->image->store('updloads', 'public'),
]);
}
}

Related

How to bulk upload images in Laravel

This is the code that i use now, this works for uploading single images, but i want the option to choose multiple images at the same time and upload them to the s3 bucket.
public function create() {
return view(view: 'images.create');
}
public function store(Request $request) {
$path = $request -> file(key: 'image') -> store(path: 'images', options: 's3');
$image = Image::create([
'filename' => basename($path),
'url' => Storage::disk(name: 's3') -> url($path)
]);
return $image;
}
public function show(Image $image) {
return $image -> url;
}
I have been looking into the answer to this question: Uploading multiple files to Amazon S3 from PHP
But struggle to understand and how to implement it into my own code.

Problem with multiple image upload in laravel 8

I have to make an online shop website and I have to make multiple image uploads inside my product's form and then display it as a slideshow in my view. I tried 5 tutorials or their concepts and nothing works. I'm so frustrated, so if you guys know anything, hit me up. I'm hoping to find simplest and straight-forward way to store images in database and display them. I'm not good in back-end stuff but I'm trying to learn the ropes.
If you wanna know what I've worked so far is i have two tables linked up which are images and foods. then, images table has a foreign key that will get id from the foods table. That will help the system to know which image is referring to which kind of food. Based on the tutorial that I've have tried so far and the best one I've tried, I got it uploaded in database but the filename only showed []. I've checked inside my public folder too, and I couldn't find the files that I uploaded in there. I tried to display it on view and it throws a messed up error. I was really confused and stressed out just because of this function.
this is the code from my controller (getwelcome is my index):
public function getWelcome(Food $foods)
{
$data = Images::all();
return view('welcome', compact('foods', 'data'));
}
public function store(Request $request)
{
$foods = new Food([
'name' => $request->get('name'),
'description' => $request->get('description'),
'price' => $request->get('price'),
// column name => front-end name
]);
$foods->save();
if ($request->hasfile('filename')) {
foreach ($request->file('filename') as $image) {
$name = $image->getClientOriginalName();
$image->move(public_path() . '/images/', $name); // folder path
$data[] = $name;
}
}
$Upload_model = new Images;
$Upload_model->food_id = $foods->id;
$Upload_model->filename = json_encode($data);
$Upload_model->save();
session()->flash('success', 'Food successfully added.');
return redirect()->route('welcome');
}
image migration
Schema::create('images', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('food_id');
$table->String('filename');
$table->timestamps();
$table->foreign('food_id')
->references('id')
->on('food')
->onDelete('cascade');
});
in my view
#foreach($data as $image)
#foreach(json_encode($image->filename)as $picture)
<div class="mySlides fade">
<img src="{{ asset('/images'.$picture) }}" style="width:295px; height:295px">
</div>
#endforeach
#endforeach
Your mistake is calling json_encode in your view. The field is already a string, you need to "decode" it out of JSON into something PHP can use:
#foreach (json_decode($image->filename) as $image)
...{{ asset('images/'. $image) }}...
if ($files = $request->file('images')) :
foreach ($files as $file) :
$extension = $file->extension();
$imageName = time() . rand(1, 100) . '.' . $extension;
$file->storeAs('/public/image/product/multiple', $imageName);
$arr[] = $imageName;
endforeach;
$image = implode(",", $arr);
$product->m_image = $image;
else :
$image = '';
endif;

I can't see my update profile image using laravel 6

i am trying to update the image of profil ,because to user at the beginning it creates account without image, after it goes the update, so i store the image in root /aswakfolder/public/storage/profiles and i insert image link in db profiles/nameimage.jpeg, i created a function in helpers.php file to display the image its work very will, the problem here is that I do not understand the helpers function, and it does not meet my needs, my need is when image upload and exists it displays my image if not it displays image not-found.jpeg,in my case it always displays not-found.jpeg.
stock image in my folder, and url image insert in db very well.
UsersController.php
public function update(Request $request, $id)
{
$user=User::find($id);
if($request->hasFile('image'))
{
$image = $request->file('image');
$path = $request->image->store('profiles');
$user->image = $path;
}
$request->image = $user->image;
$user->id = Auth::user()->id;
$user->update([
$user->name => $request->name,
$user->email => $request->email,
$user->telephone => $request->telephone,
$user->daten => $request->daten,
$user->country_id=> $request->country_id,
$user->state_id => $request->state_id,
$user->city_id => $request->city_id,
$user->image => $request->image,
]);
session()->flash('success', 'user updated successfully !!');
return redirect('users');
}
helpers.php
function productImage($path)
{
return $path && file_exists('/aswakfolder/public/storage/'.$path) ? asset('/aswakfolder/public/storage/'.$path) : asset('/aswakfolder/public/storage/not-found.jpg');
}
index.blade.php
<div class="inner" style="background-image: url({{ asset(productImage($users->image)) }})">
Make sure you run the commend php artisan storage:link to create the shortcurt on public/ folder.
Documentation

Problem with deleting images from database in Laravel

I am trying to delete images from database in Laravel using Postman. I have products and images that are connected through polymorphic relationship. I get error in Postman undefined index images, but when I put that in isset function I no longer get error but just empty screen in postman and it doesn't delete image from database. When I dump validation variable I get empty array. And strange thing happens in my browser when I click on delete button on that image then it erases it in database, but it won't using Postman. Any help is appreciated. Here is my code.
api.php
Route::delete('/products/images/delete', 'ProductController#deleteImage')->name('products.images.delete');
ProductController.php
public function deleteImage(Request $request)
{
$validation = request()->validate([
'image_ids.*' => 'required'
], $request->all());
dd($validation); HERE IT BREAKS AND IT SHOWS EMPTY ARRAY!
try {
$this->service->deleteImage($validation['image_ids']);
return $this->successJson(['success'=> 'Image deleted successfully!'], 200);
} catch (\Exception $exception) {
return $this->failureJson($exception);
}
}
ProductService.php
public function deleteImage($imageIds)
{
$this->imageService->destroyModelImages($this->product, $imageIds);
}
ImageService.php
public function destroyModelImages(Model $model, Array $ids)
{
$pathToFolder = $this->pathToFolderWithImages($model);
foreach ($ids as $imageId) {
$image = $model->images->find($imageId);
Storage::disk($this->disk)->delete($pathToFolder . '/' . $image->name);
$image->delete();
}
$this->deleteFolderIfIsEmpty($pathToFolder);
}

how to delete multiple records that involve images in laravel

Please guys any idea how to delete multiple records that involve images. i do not know any approach that i can use. i have tried a lot.this is the what i have tried below.Pls help me guys i really need your help.Thanks in advance
please this is the code below
public function multipleUserDelete(Request $request,$id, $post_image){
if ($request->isMethod("post")) {
$data=$request->all();
//$del_user = $request->del_user;
// $ids=$del_user[];
//foreach(session('posts') as $session){
//foreach(session('products') as $postDelete){
$postDeletes=Post::where(['id'=> $id])
->where('post_image', $post_image)
->get();
foreach ($postDeletes as $postDelete) {
# code...
// $postDeletes=Post::where(['id'=> $id])->get();
//}
$large_image_paths='images/backend_image/admin_users/small/';
$medium_image_paths='images/backend_image/admin_users/medium/';
$small_image_paths='images/backend_image/admin_users/large/';
//Delete Image permenently from product table begins
//Delete Large image if not exist
if(file_exists($large_image_paths. $postDelete->post_image)){
unlink($large_image_paths. $postDelete->post_image);
}
//Delete Large image if not exist
if(file_exists($small_image_paths. $postDelete->post_image)){
unlink($small_image_paths. $postDelete->post_image);
}
//Delete Medium image if not exist
if(file_exists($medium_image_paths. $postDelete->post_image)){
unlink($medium_image_paths. $postDelete->post_image);
}
}
//$del_id=$request->input('del_feedback');
Post::whereIn('id', $data['del_user'])->delete();
return redirect()->back()->with("flash_message_success","you Successfully Deleted The Selected Users(s)");
}
Not tested, but I think something like this should work fine.
$image_path = "/images/"; // Value is not URL but directory file path
Post::where(['id'=> $id])
->where(function($query){
if(File::exists($image_path . $post_image)) {
File::delete($image_path . $post_image);
}
$query->where('post_image', $post_image)
})
->delete();
In general, the path issue should probably be
absolute.
See How to delete file from public folder in laravel 5.1
I don't know in Laravel 6, but it should work.
i.e. using File :: delete ()
Add the folder that contains your image to your config/filesystems.php files:
'disks' => [
'local' => [
'driver' => 'local',
'root' => base_path('app'),
],
//Above bit should already be there. So add this....
'some-image-path' => [
'driver' => 'local',
'root' => base_path("wherever/your/directory/is/from/root/"),
],
You would then use it like this:
$myImage = 'some-image.png';
Storage::disk('some-image-path')->delete($myImage);
public function multipleUserDelete(Request $request,$id, $post_image){
if ($request->isMethod("post")) {
$data=$request->all();
$postDeletes=Post::where(['id'=> $id])
->where('post_image', $post_image)
->get();
$img_array = array();
foreach ($postDeletes as $postDelete) {
$large_image_paths='images/backend_image/admin_users/small/';
$medium_image_paths='images/backend_image/admin_users/medium/';
$small_image_paths='images/backend_image/admin_users/large/';
$img='';
if(file_exists(public_path($large_image_paths. $postDelete->post_image))){
$img = $large_image_paths. $postDelete->post_image;
}
if(file_exists(public_path($small_image_paths. $postDelete->post_image))){
$img = $small_image_paths. $postDelete->post_image;
}
if(file_exists(public_path($medium_image_paths. $postDelete->post_image))){
$img = $medium_image_paths. $postDelete->post_image;
}
array_push($img_array,$img);
}
\File::delete($img_array);
Post::whereIn('id', $data['del_user'])->delete();
return redirect()->back()->with("flash_message_success","you Successfully Deleted The Selected Users(s)");
}

Categories