I am working on multiple image upload in laravel. Uploading is successful but, i got an issue. For later use i should store in database. For single column it easy but for different column for different images i couldnot do it.
Here is my image upload code
$images = [];
$destDir = "public/uploads/";
if($request->file('image1')) $images[]=$request->file('image1');
if($request->file('image2')) $images[]=$request->file('image2');
if($request->file('image3')) $images[]=$request->file('image3');
foreach($images as $image)
{
if(!empty($image))
{
$imageName = $image->getClientOriginalName();
$extension = $image->getClientOriginalExtension();
$temPath = $image->getRealPath();
$enImg = mt_rand(1111,9999).".".$extension;
$newPath = $destDir.$enImg.".".$extension;
move_uploaded_file($temPath, $newPath);
}
}
I have a feeling you are approaching this in a way that is making it more difficult for you. Instead of creating multiple separate file inputs in your form you can only set a multiple file input and set the name of the input to an array like so:
<form action="demo_form.asp">
Images: <input type="file" name="images[]" multiple>
<input type="submit">
</form>
Then in your php you can do something like this:
if (isset($request->all()['images'])) {
$this->persistUserImages($request->all()['images'], $userId);
}
/**
* Persists user images to storage and DB
*
* #param array $userImages
* #param int $userId
* #return array
*/
private function persistUserImages(array $userImages, $userId = 1)
{
if (empty($userImages)) {
return [];
}
$uploadedUserImagesFilenames = $this->uploadUserImagesToCloud($userImages, $userId);
foreach ($uploadedUserImagesFilenames as $filename) {
$userImage = new UserImage([
'user_id' => $userId,
'filename' => $filename,
'visible' => 1
]);
$userImage->save();
}
}
You can do like this this. In your blade,
<form action="{{url('path')}}" methos="post" enctype="multipart/form-data">
Images: <input type="file" name="images[]" multiple>
<input type="submit">
</form>
In you method,
public function store(Request $request){
foreach ( $request->images as $image) {
Model::create([
'image_url' => $image,
]);
}
}
Or
follow below link. It's very easy way to solve this problem.
Multiple Image Upload In Laravel
Hope you can solved your problem.
create a pivot table and store images in separate rows..
Table schema:- `images` table
columns `id`,`user_id`(foreign key),`image_path`
store your $newPath in this table every time..
Related
I am trying to edit/update an image in a user table, when I select a new image and submit the form the image name doesn't get stored in the database instead this C:\wamp64\tmp\phpAE1C.tmp get saved in the image column, I don't know why, Please help if u know why.
The UsersController
public function update(Request $request, $id)
{
$request->validate([
'name' => 'required|string|max:225',
'email' => 'required|string|email|max:255|unique:users,email,'.auth()->id(),
'password' => 'sometimes|nullable|string|min:6|confirmed',
]);
$user = auth()->user();
//Handle avatar Upload
if ($request->hasFile('avatar')) {
// Get filename with extention
$filenamewithExt = $request->file('avatar')->getClientOriginalName();
// Get just filename
$filename = pathinfo($filenamewithExt, PATHINFO_FILENAME);
// Get just Extention
$extention = $request->file('avatar')->getClientOriginalExtension();
// Filename to store
$filenameToStore = $filename.'_'.time().'.'.$extention;
// Upload Image
$path = $request->file('avatar')->storeAs('public/avatars', $filenameToStore);
}
if ($request->hasFile('avatar')) {
$user->avatar = $filenameToStore;
}
//Handle image Upload
if ($request->hasFile('image')) {
// Get filename with extention
$ImageNameWithExt = $request->file('image')->getClientOriginalName();
// Get just filename
$ImageName = pathinfo($ImageNameWithExt, PATHINFO_FILENAME);
// Get just Extention
$Extentions = $request->file('image')->getClientOriginalExtension();
// Filename to store
$ImageNameToStore = $ImageName.'_'.time().'.'.$Extentions;
// Upload Image
$paths = $request->file('image')->storeAs('public/images', $ImageNameToStore);
}
if ($request->hasFile('image')) {
$user->image = $ImageNameToStore;
}
$user->save();
$input = $request->except('password', 'password_confirmation');
if (!$request->filled('password')) {
$user->fill($input)->save();
return back()->with('success', 'Profile updated successfully!');
}
$user->password = bcrypt($request->password);
$user->fill($input)->save();
return back()->with('success', 'Profile and password updated successfully');
}
The image input field in edit.blade
<div class="form-group col-md">
<div class="custom-file">
<input type="file" name="image" class="custom-file-input" id="customFile" >
<label class="custom-file-label text-align-left" style="text-align:left;"
for="customFile">Choose file</label>
</div>
</div>
I suggest you to change this :
$input = $request->except('password', 'password_confirmation');
to,
$input = $request->except('password', 'password_confirmation','image','avatar');
if ($request->hasFile('image')) {
$input['image'] = $ImageNameToStore;
}
if ($request->hasFile('avatar')) {
$input['avatar'] = $filenameToStore;
}
When using fill or update to persist Request data, it's always better to exclude the image fields. For any uploaded images in the request data it doesn't make much sense to store raw image data in database.
Rather the image can be stored on either local disk or something like S3 and the path to the saved image should be stored in database corresponding to the image field like avatar
I am having some issue while trying to upload multiple images on the back end in Laravel. I have a simple form with an input field and a multiple attribute that should upload an array of images in the database but whatever I try, I get the same error 'The "" file does not exist or is not readable'. I checked the names in the input field and they are the same as the name in the file() method. Any help is appreciated.
PS: Am a newbie to Laravel and PHP...
ProductController:
foreach($request->file('images')->store('images') as $images) {
$product->images()->create([
'images' => $images
]);
}
Blade file:
<form method="POST" enctype="multipart/form-data">
#csrf
<h5>Upload Multiple Images</h5>
<input type="file" multiple name="images" id="images"> Upload Images
</form
I know this is an old question, but I had the same issue a few days ago. Hope this helps anyone.
I solved the problem by setting php_value upload_max_filesize in php.ini over the size of my uploaded file.
This is where I found the answer in case you are interested:
If someone else gets this error and it doesn't turn out to be a permissions issue, check your php.ini...make sure that your upload_max_filesize is as big as your post_max_size. I had 1000M for post_max_size (we deal with some big ol' video files), but only 100M for upload_max_size (I blame my old eyes). The upload would churn for a long time, and then throw the error above.
https://github.com/laravel/framework/issues/31249
Try..
$input = $request->all();
$datas = [];
if ($request->hasfile('images')) {
foreach ($request->file('images') as $key => $file) {
$name = $file->getClientOriginalName();
$file->move(public_path() . '/your path /', $name); //if you want to store image in yopur folder
$datas[$key] = $name;
$file = new YourMOdelNAme();
foreach ($datas as $data) {
$file->images = $data;
$file->save();
}
}
}
name images array
<form method="POST" enctype="multipart/form-data">
#csrf
<h5>Upload Multiple Images</h5>
<input type="file" multiple name="images[]" id="images"> Upload Images
</form
Upload files using below code
$files = $request->file('images');
if($request->hasFile('images'))
{
foreach ($files as $file)
$product->images()->create([
'images' => $file
]);
}
I have an order and I want to after save, get in session current id of order for next page reports.
use Session;
public function store(Request $request)
{
$order = new Order($request->all());
$order->user_id = auth()->user()->id;
$order->title = $request->title;
$order->body = $request->body;
$order->id = $request->session()->get('id');
$order->description = $request->description;
$order->save();
session(['order_id' => $order_id]);
return redirect()->route('reports.index')->with('order_id', $request->id);
}
In notes page has a input hidden for get session of article id.
<input type="hidden" class="form-control" value="{{ Session::get('order_id') }}" name="id" id="id">
But I see input hidden. It is blank . "".
I'm confused here
session(['order_id' => $order_id]);
return redirect()->route('reports.index')->with('order_id', $request->id);
when you're returning something with "->with()" it stores in session so why use session() ? and $order_id is not defined in your method.
and best way to put something in session is like this
Session::put('order_id');
I think if you do this
->with('order_id', $order->id); // You will get the current order id created
The problem:
I want to upload an image to a mySQL database using Laravel.
what I have tried:
I looked for other stack-overflow questions but they weren't helpful.
the result I am expecting :
is to have the image name or path saved to a column in my table on the database , to retrieve and display it later as a post in a blog.
First you need the form on your view (don't forget the csrf token):
<form action="/image-upload" method="POST" enctype="multipart/form-data">
#csrf
<input type="file" name="image">
<button type="submit">Upload</button>
</form>
And on your routes file add the route for POST method:
Route::post('image-upload', 'ImageUploadController#imageUploadPost');
Then on your Controller create the function that will validate and move your image to the 'public/images' folder.
public function imageUploadPost()
{
request()->validate([
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$imageName = time().'.'.request()->image->getClientOriginalExtension();
request()->image->move(public_path('images'), $imageName);
}
For better solution please read this: Laravel File Storage
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. 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)
));
});
NOTE: Please have this in your mind, MySQL isn't a suitable solution to store BLOB. You may need to use an object storage service like Amazon S3.
Use this to upload image
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
// $this->validate($request,[//'movie_name'=>'required',
// // 'description'=>'required',
// //'video_url'=>'required',
// 'image'=>'required|mimes:jpeg,jpg,png,gif|required|max:10000',
// ]);
if ($request->hasFile('image') && $request->hasFile('image2')) {
$file = $request->file('image');
//$image=$file->getClientOriginalName();
$image = time().'.'.$file->getClientOriginalExtension();
$destinationPath ='assets/admin/uploads/image/';
$file->move($destinationPath,$image);
//echo $destinationPath;exit();
//echo $image."<br/>";
$file2 = $request->file('image2');
$bg_images = time().'.'.$file2->getClientOriginalExtension();
//$bg_images=$file2->getClientOriginalName();
$destinationPath ='assets/admin/uploads/bg_images/';
$file2->move($destinationPath,$bg_images);
$insert_data=array('movie_name'=>$request->movie_name,
'description'=>$request->description,
'video_url'=>$request->video_url,
'image'=>$image,
'bg_images'=>$bg_images,
'created_at'=>now(),
'updated_at'=>now()
);
//print_r($insert_data);exit();
}
else
{
if ( $request->hasFile('image2')) {
$file2 = $request->file('image2');
$bg_images = time().'.'.$file2->getClientOriginalExtension();
//$bg_images=$file2->getClientOriginalName();
$destinationPath ='assets/admin/uploads/bg_images/';
$file2->move($destinationPath,$bg_images);
//echo $destinationPath;exit();
//echo $bg_images;
$insert_data=array('movie_name'=>$request->movie_name,
'description'=>$request->description,
'video_url'=>$request->video_url,
//'image'=>$image,
'bg_images'=>$bg_images,
'created_at'=>now(),
'updated_at'=>now()
);
//print_r($insert_data);exit();
}
if ($request->hasFile('image') ) {
$file = $request->file('image');
//$image=$file->getClientOriginalName();
$image = time().'.'.$file->getClientOriginalExtension();
$destinationPath ='assets/admin/uploads/image/';
$file->move($destinationPath,$image);
//echo $destinationPath;exit();
//echo $image."<br/>";
$insert_data=array('movie_name'=>$request->movie_name,
'description'=>$request->description,
'video_url'=>$request->video_url,
'image'=>$image,
//'bg_images'=>$bg_images,
'created_at'=>now(),
'updated_at'=>now()
);
// print_r($insert_data);exit();
}
if ( ! $request->hasFile('image2') && ! $request->hasFile('image') ) {
$insert_data=array('movie_name'=>$request->movie_name,
'description'=>$request->description,
'video_url'=>$request->video_url,
//'image'=>$image,
// 'bg_images'=>$bg_images,
'updated_at'=>now()
);
// print_r($update_data);exit();
}
}
//exit();
// echo $image;
//exit();
//print_r($insert_data);exit();
$insert=DB::table('movies')->insert($insert_data);
if ($insert) {
return redirect()->route('admin.list_movies')->withSuccess('Record saved');
}
else {
return redirect()->route('admin.list_movies')->withError('Record not saved');
}
}
I want to calculate the minimum value from a collection of form fields.
I have one-to-many relationship, where one shop can have many items ans that is working fine without any errors.
My form
<form action="{{ route('form_submit') }}" method="post">
#csrf
<h3>Item 1</h3>
<input type="text" name="item[]">
<input type="text" name="price[]">
//Like this I can add many fields
<input type="submit">
</form>
Controller
public function store(Request $request, $id){
$shop = Shop::findorfail($id);
$item = Item::where('shop_id', $shop->id)->get(); //working fine
$i=0;
$price = request('price')
foreach( $items as $item)
$item->price = request('price')[$i];
$i++;
//I tried
$price_group = collect($item->price)->where('shop_id', $shop->id);
$min_price = min($price_group);
$item->save();
}
Route
Route::post('/{id}', 'Controller#store')->name('form_submit');
But it does not calculate the minimum price. When I dd($min_price), its total blank. What am I missing here?
I think is just...
$items = Item::where('shop_id', $shop->id)->get();
$min = $items->min('price');
And take a look on eager loading for relations. It's much better.
I solved this by #Jonas's solution. And I make this my answer.
Controller
public function store(Request $request, $id){
$shop = Shop::findorfail($id);
$item = Item::where('shop_id', $shop->id)->get(); //working fine
$i=0;
$price = request('price')
foreach( $items as $item)
$item->price = request('price')[$i];
$i++;
//This works
$min_price = min(request('price'));
$item->save();
}