How to upload an image using Laravel? - laravel

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');
}
}

Related

Image saving in database as C:\wamp64\tmp\phpAE1C.tmp instead of saving in public/images

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

Multiple Image Upload in Laravel tweak to add additional field

I have a need to upload multiple images. This code below works well. This is using Intervention Image plugin. I am trying to customise this code to add another field which is a ForeignKey value to the parent of this image model. $request has the value coming from form. How to save it along with images?
The value is:
$request('vehicle_id')
How can tweak the below method so as save includes this vehicle_id as well?
public function uploadImage(Request $request)
{
$request->validate([
'image' => 'required',
'image.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'
]);
//check if image exist
if ($request->hasFile('image')) {
$images = $request->file('image');
// create new directory for uploading image if doesn't exist
if( ! File::exists('images/'.auth()->user()->id)) {
$org_img = File::makeDirectory('images/'.auth()->user()->id, 0777, true);
}
// loop through each image to save and upload
foreach($images as $key => $image) {
//create new instance of Photo class
$newPhoto = new $this->photo;
//get file name of image and concatenate with 4 random integer for unique
$filename = rand(1111,9999).time().'.'.$image->getClientOriginalExtension();
//path of image for upload
$org_path = 'images/'.auth()->user()->id . $filename;
$newPhoto->image = 'images/'.auth()->user()->id.$filename;
//don't upload file when unable to save name to database
if ( ! $newPhoto->save()) {
return false;
}
// upload image to server
if ($org_img == true) {
Image::make($image)->fit(900, 500, function ($constraint) {
$constraint->upsize();
})->save($org_path);
}
}
}
return redirect('/home')->with('success','Images Uploaded');
}
I found solution
public function uploadImage(Request $request)
{
$request->validate([
'image' => 'required',
'image.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048',
'vehicle' => 'required'
]);
//check if image exist
if ($request->hasFile('image')) {
$images = $request->file('image');
// create new directory for uploading image if doesn't exist
if( ! File::exists('images/'.auth()->user()->id.'/')) {
$org_img = File::makeDirectory('images/'.auth()->user()->id.'/', 0777, true);
}
// loop through each image to save and upload
foreach($images as $key => $image) {
//create new instance of Photo class
$newPhoto = new $this->photo;
//get file name of image and concatenate with 4 random integer for unique
$filename = rand(1111,9999).time().'.'.$image->getClientOriginalExtension();
//path of image for upload
$org_path = 'images/'.auth()->user()->id.'/' . $filename;
$newPhoto->image = 'images/'.auth()->user()->id.'/' . $filename;
$newPhoto->vehicle = $request->input('vehicle');
//don't upload file when unable to save name to database
if ( ! $newPhoto->save()) {
return false;
}
// upload image to server
Image::make($image)->fit(900, 500, function ($constraint) {
$constraint->upsize();
})->save($org_path);
}
}
return redirect('/home')->with('success','Images Uploaded');

How to store multiple images paths into database in laravel?

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

image upload code is not working

i am new in laravel, i am facing a big problem and i can't solve this problem.
I am trying to upload image into my database and upload folder,but my code is not working,
Here is my controller code
public function store()
{
$rules=array(
'gallery_name'=>'required',
'image_title'=>'required',
'image'=>'required'
);
$file = Input::file('image');
$destinationPath = 'uploads/';
// If the uploads fail due to file system, you can try doing public_path().'/uploads'
$filename = str_random(32) . '.' . $file->getClientOriginalExtension();
//$filename = $file->getClientOriginalName();
//$extension =$file->getClientOriginalExtension();
//get all book information
$galleryInfo = Input::all();
//validate book information with the rules
$validation=Validator::make($galleryInfo,$rules);
$upload_success = Input::file('image')->move($destinationPath, $filename);
if($validation->passes())
{
//save new book information in the database
//and redirect to index page
if ($upload_success) {
//save in the Band table database
Gallery::create($galleryInfo);
return Redirect::route('galleries.index')
->withInput()
->withErrors($validation)
->with('message', 'Successfully created Gallery.');
}
else {
return Redirect::route('galleries.create')
->withInput()
->withErrors($validation)
->with('message', 'Image fields are incomplete.');
}
}
//show error message
return Redirect::route('galleries.create')
->withInput()
->withErrors($validation)
->with('message', 'Some fields are incomplete.');
}
please help me as soon.
Thank you.

how to encode image decoded by base64_decode, symfony

I have a image decode by base64_decode.
I have a entity Image. This is entity consist : id and path to the file. File of image load to server by this guide http://symfony.com/doc/current/cookbook/doctrine/file_uploads.html.
How encode this string and upload file to server and upload path to database in controller.
my controller
public function updateattachmentAction()
{
$em = $this->getDoctrine()->getManager();
$photo = $em->getRepository('MyPluginBundle:Photo')->findOneById(4);
$str="";
$request = $this->container->get('request');
$image = $request->query->get('image');
// file_put_contents($photo, base64_decode($data));
// $photo->upload();
// $em->persist($photo);
// $em->flush();
$response = array("code" => 100,"success" => true);
//you can return result as JSON
return new Response(json_encode($response));
}
it should help DataUriNormalizer
https://symfony.com/blog/new-in-symfony-3-1-data-uri-normalizer## Heading ##
use Symfony\Component\Serializer\Normalizer\DataUriNormalizer;
$normalizer = new DataUriNormalizer();
$avatar = $normalizer->denormalize('data:image/gif;base64,R0lGODdhAQABAIAAAP///////ywAAAAAAQABAAACAkQBADs=', 'SplFileObject');
// $avatar is a SplFileObject with the GIF image contents
and this https://github.com/hshn/base64-encoded-file
use Hshn\Base64EncodedFile\HttpFoundation\File\Base64EncodedFile;
$file = new Base64EncodedFile(base64_encode($data));
$file->getPathname(); // "/path/to/file"
$file instanceof Symfony\Component\HttpFoundation\File\File; // true

Resources