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;
Related
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
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'),
]);
}
}
I am building a classified website and I am trying to set it up to show one photo from the database on the main page, that same photo on a category page, but when you view the full page of the item for sale I want to show all of the photos in that section.
Like how ebay shows one photo for the ad but when you click the ad it shows several photos.
I have used 'strtok' to show the single photo in my main page and category page but now I don't know how to setup the view page to show all the photos for that item.
here is how I am saving the images when the listing is posted.
public function postHobbies(Request $request)
{
$this->validate($request, [
'photos' => 'required',
'Photos.*' => 'image|mimes:jpg, png, jpeg, gif, aae, heif, svg|max:2048'
]);
$ads = new Listings;
$images = $request->file('photos');
$count = 0;
if ($request->file('photos')) {
foreach ($images as $item) {
if ($count < 6) {
$var = date_create();
$date = date_format($var, 'Ymd');
$imageName = $date . '_' . $item->getClientOriginalName();
$item->move(public_path() . '/uploads/', $imageName);
$url = URL::to("/") . '/uploads/' . $imageName;
$arr[] = $url;
$count++;
}
}
$image = implode(",", $arr);
$ads->photos = $image;
$ads->save();
return redirect('/')->with('info', 'Listing published successfully');
}
}
here is my controller for the page I am trying to post all of the photos on
public function view(Request $request, $id)
{
$ads = DB::table('listings')
->select('listings.id', 'photos', 'description', 'year', 'make', 'model', 'price', 'city', 'state', 'email')
->where(['id' => $id])
->get();
$output = '';
if ($ads->count() > 0) {
return view('users.posted.postedads', ['id' => $id, 'ads' => $ads]);
}
}
And finally here is how I am currently passing it which is just showing me the single photo since I am still using the 'strtok' to make sure it works. So i assume i need to change this function i just don't know what to use or how to use it.
<div class="row">
#if(count($ads)>0)
#foreach($ads as $row)
<div class="col-md-12">
<div class="productCard">
<img style="width:100%; height:100%;" src="<?php echo strtok($row->photos, ',')?>" />
</div>
</div>
#endforeach
#else
#endif
First of all, you need to save many images, you are saving only one image now.
It is recommended to make another model for images (for example Image), and make one to many or many to many relationships between Listings(it is better to user singular name for models).
Then, in your view method you need to retrieve related models with Listings->with('images') and in your view file, you need add another foreach loop where you want to display images.
View code would be something like this:
<div class="row">
#if(count($ads)>0)
#foreach($ads as $row)
<div class="col-md-12">
<div class="productCard">
#foreach($row->images as $image)
<img style="width:100%; height:100%;" src="{{ $image->url }}" />
#endforeach
</div>
</div>
#endforeach
#else
#endif
Note I used {{ }} Laravel Blade directive instead of <?php echo, you should too
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)");
}
I have to store and retrieve an image from the database.
I want to store an image instead of image path or image name. When I searched for it I only found solutions for storing an image path or name. So can someone tell me how to store and retrieve an image with its size in KBs from database?
This is my route.
Route::get('big_image/{id}/image', function ($id)
{
$user = big_image::find($id);
return response()->make($user->image, 200, array(
'Content-Type' => (new finfo(FILEINFO_MIME))->buffer($user->image)
));
});
This is my controller
public function new_store(Request $request ,$id){
$event_id = $id;
$img = new big_image;
$file = $request->file('image');
$contents = $file->openFile()->fread($file->getSize());
$img = big_image::find($id);
$img->image = $contents;
$img->image_name = $request->image_name;
$img->event_id = $event_id;
$img->save();
$images=DB::table('big_image')->where('event_id','=',$event_id)->get();
return view('image_upload',compact('images','id','response'));
}
My display.blade.php file
#extends('app')
#section('content')
<h2 style="text-align: center;margin-top: 10px;">Image Gallery</h2>
<span> add more pictures</span><br>
<span>Back to events</span><br>
#foreach($images as $item)
<div class="col-sm-4">
{{--<img src="data:image/jpeg;base64,'.base64_encode( $item->image ).'"/>;--}}
</div>
#endforeach
#stop
Actually with Laravel it only involves a few lines of code. Let's say you have a user that has an avatar which is stored in the database. Assuming you're using MySQL, here's how you would store and retrieve the avatar from the database:
1. First you'll need to have an avatar column in the users table that can store binary data. Depending on how large you want to allow the avatar image to be, the data type of the column can be one of the following:
BLOB up to 64KB
MEDIUMBLOB up to 16MB
LONGBLOB up to 4GB
2. To store the uploaded image in the database you can do this:
Route::post('user/{id}', function (Request $request, $id) {
// Get the file from the request
$file = $request->file('image');
// Get the contents of the file
$contents = $file->openFile()->fread($file->getSize());
// Store the contents to the database
$user = App\User::find($id);
$user->avatar = $contents;
$user->save();
});
3. To fetch and ouput the avatar you can do the following:
Route::get('user/{id}/avatar', function ($id) {
// Find the user
$user = App\User::find(1);
// Return the image in the response with the correct MIME type
return response()->make($user->avatar, 200, array(
'Content-Type' => (new finfo(FILEINFO_MIME))->buffer($user->avatar)
));
});
So to access the avatar of the user with an id equal to 10 you can just use this URL:
http://domain.com/user/10/avatar
You can store files in database in blob fields.
Maybe this link helps you
Then You can create url to your image:
Route::get('/images/{image}', function($image)
{
header("Content-type: image/jpeg");
//"select image from table where id = $image"
echo $here_I_get_my_img_from_DB;
});
and get img from url: /image/{img_id}