Getting error in Laravel 6.0 while upload image to database - php

I'm new to Laravel and using Laravel 6.0. While uploading image I am getting error of SplFileInfo::getSize(): stat failed for C:\xamp\tmp\php14F3.tmp
I searched for solution on google yet couldn't find any solution.
This is my controller function
public function store(PostsCreateRequest $request)
{
//
$input = $request->all();
$user = Auth::user();
if ($request->hasfile('photo_id')) {
$file = $request->file('photo_id');
$name = time() .$size. $file->getClientOriginalName();
$file->move('posts' , $name);
$photo = Photo::create(['path'=>$name]);
$input['photo_id'] = $photo->id;
}
$user->posts()->create($input);
Session::flash('created_post',"The Post has been created");
return redirect('/home');
}

My solution is
use Illuminate\Http\Request; this request instead of old request.
public function saveimage(Request $request){
request()->validate([
'file' => 'required|mimes:jpeg,jpg|max:2048',
]);
if ($files = $request->file('file')) {
$destinationPath = 'public/images/'; // upload path
$profilefile = date('YmdHis') . "." . $files->getClientOriginalExtension();
$files->move($destinationPath, $profilefile);
$insert['file'] = "$profilefile";
}
$check = Document::insertGetId($insert);
return Redirect::to("home")
->withSuccess('Great! file has been successfully uploaded.');
}
}
Its working fine.

Give the size of the image while giving the validation. The below code is working fine.
public function saveImage(Request $request){
$this->validate($request, [
'name' => 'required',
'description' => 'required',
'image' => 'required|image|mimes:jpeg,jpg,gif,png,svg|max:2048'
]);
$instrument = new \App\Models\Instrument;
$instrument->name = $request->input('name');
$instrument->description = $request->input('description');
$imgfile = $request->file('image');
$instrument->image = $imgfile->getClientOriginalName();
if ($imgfile !== null) {
$filenameWithExt = $imgfile->getClientOriginalName();
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
$extension = $imgfile->getClientOriginalExtension();
$fileNameToStore= $filename.'_'.time().'.'.$extension;
$imgfile->storeAs('public/images', $fileNameToStore);
} else {
//dd("Image Not Uploaded");
}
$instrument->save();
return redirect('/instruments')->with('success', 'Details are uploaded successfully');
}

Related

How to get the id from another post form when using a multiple image uploader using laravel?

I have two forms the blog post and multiple image uploader, basically I want to use multiple image uploader in the blog post form, however I need to get the ID from blog post form so each blog posts has it's own unique set of images. I am aware you can use foreign keys to establish the link between the two tables but I am unsure how to do this. Right now the blog post form only does a single file upload so I want a way to use the multiple image uploader logic into the PostController which then saves into the images table. Really appreciate the help thank you.
ImagesController
public function store(Request $request)
{
if(!$this->validate($request, [
'id' => 'integer',
'images.*' => 'sometimes|image|nullable|mimes:jpeg,png,jpg,gif,svg,webp|max:25000',
'post_id' => 'required'
])) {
return redirect()->back()->with('errors');
}
if($request->hasfile('images'))
{
foreach($request->file('images') as $image)
{
$filenameWithExt = $image->getClientOriginalName();
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
$extension = $image->getClientOriginalExtension();
$fileNameToStore = $filename.'_'.time().'.'.$extension;
$path = $image->storeAs('public/image', $fileNameToStore);
$image = new Images;
$image->images = $fileNameToStore;
$image->post_id = $request->post_id;
$image->save();
}
}
return back()->with('Images have been uploaded!');
}
PostController
public function store(Request $request)
{
// Validate posted form data
$validated = $request->validate([
'id' => 'integer',
'vehicle' => 'required|string',
'h1' => 'required|string',
'page_title' => 'required|string',
'meta_description' => 'required|string',
'image' => 'sometimes|image|nullable|max:5000',
'content' => 'required|string',
'active' => 'integer',
'user_id' => 'required'
]);
// Create slug from title
$validated['slug'] = Str::slug($validated['vehicle'], '-');
$validated['active'] = isset($request->active[0]) ? 1 : 0;
if($request->hasFile('image'))
{
$filenameWithExt = $request->file('image')->getClientOriginalName();
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
$extension = $request->file('image')->getClientOriginalExtension();
$fileNameToStore = $filename.'_'.time().'.'.$extension;
$path = $request->file('image')->storeAs('public/image', $fileNameToStore);
}else {
$fileNameToStore = null;
}
// Create and save post with validated data
$post = new Post;
$post->id = $request->input('id');
$post->vehicle = $request->input('vehicle');
$post->slug = $request->input('slug');
$post->h1 = $request->input('h1');
$post->page_title = $request->input('page_title');
$post->meta_description = $request->input('meta_description');
$post->image = $fileNameToStore;
$post->content = $request->input('content');
$post->active = $validated['active'];
$post->user_id = $request->input('user_id');
$post->slug = $validated['slug'];
$post->save();
// Redirect the user to the created post with a success notification
return redirect(route('admin.posts.show', $post))->with('notification', 'Post created!');
}
You can store images in your PostController.
Remove this part in your PostController (in store() method):
if($request->hasFile('image'))
{
$filenameWithExt = $request->file('image')->getClientOriginalName();
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
$extension = $request->file('image')->getClientOriginalExtension();
$fileNameToStore = $filename.'_'.time().'.'.$extension;
$path = $request->file('image')->storeAs('public/image', $fileNameToStore);
}else {
$fileNameToStore = null;
}
And after creating the post put the loop to save images. Change this line:
$image->post_id = $request->post_id;
to this:
$image->post_id = $post->id;
First use the Images model at the top of the PostController. Your new loop should looks like this:
if($request->hasfile('images'))
{
foreach($request->file('images') as $image)
{
$filenameWithExt = $image->getClientOriginalName();
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
$extension = $image->getClientOriginalExtension();
$fileNameToStore = $filename.'_'.time().'.'.$extension;
$path = $image->storeAs('public/image', $fileNameToStore);
$image = new Images;
$image->images = $fileNameToStore;
$image->post_id = $post->id;
$image->save();
}
}
Then (based on relationships in your models) you can access the image with something like this:
#foreach($post->images as $image)
<img src="public/image{{ $image->fileNameToStore">
#endforeach

Unable to upload image with laravel after fetch

I am trying to upload an image from my react native project using laravel as my backend framework.
This is the data I send :
I receive a warning that my network request failed.
Here is my backend code :
public function upload(Request $request)
{
$image = $request->get('data');
$name = 'Sup';
Image::make($request->get('data'))->save(public_path('images/').$name);
$fileupload = new Fileupload();
$fileupload->filename=$name;
$fileupload->save();
return response()->json(['message' => 'Success']);
}
I have a function, you can try it!
Please change the path before doing anything else (this is the code used to upload one - multiple files at once)
public function uploadImage (Request $request) {
$files = $request->file('images');
$fileText = '';
foreach($files as $file) {
$rules = array('file' => 'required|mimes:png,gif,jpeg');
$validator = Validator::make(array('file' => $file), $rules);
if($validator->passes()){
$destinationPath = 'storage/images/';
$filename = $file->getClientOriginalName();
$unique_name = md5($filename. time()).$filename;
$upload_success = $file->move($destinationPath, $unique_name);
$fileText .= url('storage/images/' . $unique_name) . '|';
}
}
return rtrim($fileText, '|');
}

How to Store Image in Database Using Laravel With Base URL

When I'm storing an image into a database, then it doesn't upload with base URL. How can resolve this type of problem in Laravel?
public function uploadimage(Request $request)
{
if ($request->hasFile('image')) {
$file = $request->file('image');
$filename = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$picture = date('His') . '-' . $filename;
$file->move(public_path('img'), $picture);
$employee_image = Image::create($request->all());
$employee_image->image = $filename;
$employee_image->save();
return response()->json(['message' => 'Image Uploaded Successfully']);
}
return response()->json(['message' => 'Select image first.']);
}
The public_path() function does not intend to be use to serve browser friendly uri, so, you should use \Illuminate\Support\Facades\URL facade instead.
e.g.:
$employee_image->image = URL::asset('storage/employees/').$filename;
$employee_image->save();
Source: Laravel.IO
Try this ....
public function uploadimage(Request $request)
{
$this->validate($request, [
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$employees = new Image($request->input()) ;
if($file = $request->hasFile('image')) {
$file = $request->file('image') ;
$fileName = $file->getClientOriginalName() ;
$destinationPath = public_path().'/images/' ;
$file->move($destinationPath,$fileName);
$employees->image = '/public/images/'.$fileName ;
}
$employees->save() ;
return response()->json(['message' => 'Image Uploaded Successfully']);
}

Update image from edit form Laravel

I want to edit the the blog form in Laravel. All other text information like Title, Body are successfully edited. But Image could not be updated. New image is not uploaded and image path is set as C:\xampp\tmp\php2030.tmp.
My Controller for edit.
public function update(Request $request, $id)
{
$requestData = $request->all();
$post = Post::findOrFail($id);
$post->update($requestData);
if ($request->hasFile('image'))
{
$file = $request->file('image');
$fileNameExt = $request->file('image')->getClientOriginalName();
$fileNameForm = str_replace(' ', '_', $fileNameExt);
$fileName = pathinfo($fileNameForm, PATHINFO_FILENAME);
$fileExt = $request->file('image')->getClientOriginalExtension();
$fileNameToStore = $fileName.'_'.time().'.'.$fileExt;
$pathToStore = public_path('media');
Image::make($file)->resize(600, 531)->save($pathToStore . DIRECTORY_SEPARATOR. $fileNameToStore);
$image = '/images/'.$fileNameToStore;
$post->save();
}
session()->flash('message', 'Successfully updated the post');
return redirect('/');
}
What is wrong with it?
When PHP receives a file upload, by default it writes it to a temporary directory like you're getting, and automatically deletes the file after the request has been handled.
What you need to do is move the uploaded file to a safe location.
Laravel 5.5 has a store method for file uploads that might be of interest.
public function update(Request $request, $id)
{
$requestData = $request->all();
$post = Post::findOrFail($id);
if ($request->hasFile('image')) {
$file = $request->file('image');
$fileNameExt = $request->file('image')->getClientOriginalName();
$fileNameForm = str_replace(' ', '_', $fileNameExt);
$fileName = pathinfo($fileNameForm, PATHINFO_FILENAME);
$fileExt = $request->file('image')->getClientOriginalExtension();
$fileNameToStore = $fileName.'_'.time().'.'.$fileExt;
$pathToStore = public_path('media');
Image::make($file)->resize(600, 531)->save($pathToStore . DIRECTORY_SEPARATOR. $fileNameToStore);
// UPDATE TEMPORARY IMAGE PATH WITH ACTUAL PATH
$requestData['image'] = "/media/{$fileNameToStore}";
}
$post->update($requestData);
session()->flash('message', 'Successfully updated the post');
return redirect('/');
}
Please, use the code below:
public function update(Request $request, $id)
{
$requestData = $request->all();
$post = Post::findOrFail($id);
$pathToStore = public_path('media');
if ($request->hasFile('image'))
{
$file = $request->file('image');
$rules = array('file' => 'required|mimes:png,gif,jpeg'); // 'required|mimes:png,gif,jpeg,txt,pdf,doc'
$validator = \Illuminate\Support\Facades\Validator::make(array('file'=> $file), $rules);
if($validator->passes())
{
$filename = $file->getClientOriginalName();
$extension = $file -> getClientOriginalExtension();
$picture = sha1($filename . time()) . '.' . $extension;
$upload_success = $file->move($pathToStore, $picture);
if($upload_success)
{
//if success, create thumb
$image = Image::make(sprintf($pathToStore.'/%s', $picture))->resize(600, 531)->save($pathToStore.'/thumb/'.$picture);
}
}
$requestData['image'] = "$pathToStore/{$picture}";
}
$post->update($requestData);
session()->flash('message', 'Successfully updated the post');
return redirect('/');
}

Resize image file laravel 5

I installed the patch "intervention/image", "must-master" in order to make my image to reduce the size of it to 300 by 300.
I've done some forms and appears to me always the same mistake.
Call to a member function resize() on string
which got the error?
Controller
public function updateProfile() {
$file = Input::file('imagem');
$profileData = Input::except('_token');
$validation = Validator::make($profileData, User::$profileData);
if ($validation->passes()) {
if ($file == null) {
User::where('id', Input::get('id'))->update($profileData);
Session::flash('message', 'Perfil editado com sucesso');
return view('backend/perfil.index');
}
$file = array_get($profileData,'imagem');
$destinationPath = 'imagens/perfil';
$extension = $file->getClientOriginalExtension();
$filename = rand(11111, 99999) . '.' . $extension;
$reduzir = $filename -> resize (300,300);
$profileData['imagem'] = $filename;
$upload_success = $file->move($destinationPath, $filename);
User::where('id', Input::get('id'))->update($profileData);
Session::flash('message', 'Perfil editado com sucesso');
return Redirect::to('backend/perfil');
} else {
return Redirect::to('backend/perfil')->withInput()->withErrors($validation);
}
}
The issue might be because of these reasons
Have you added this aliases in your app.php
'aliases' => [
//add these three at the bottom
'Form' => Illuminate\Html\FormFacade::class,
'HTML' => Illuminate\Html\HtmlFacade::class,
'Image' => Intervention\Image\Facades\Image::class
],
I believe that you already have form and html helper.
And use this function in the Controller
i.e., just pass the image and size value as the Parameter to this function
In the controller you have just call the below function like
$resizedImage = $this->resize($image, $request->get('image_size'));
And the resize() function was given below
private function resize($image, $size)
{
try
{
$extension = $image->getClientOriginalExtension();
$imageRealPath = $image->getRealPath();
$thumbName = 'thumb_'. $image->getClientOriginalName();
//$imageManager = new ImageManager(); // use this if you don't want facade style code
//$img = $imageManager->make($imageRealPath);
$img = Image::make($imageRealPath); // use this if you want facade style code
$img->resize(intval($size), null, function($constraint) {
$constraint->aspectRatio();
});
return $img->save(public_path('images'). '/'. $thumbName);
}
catch(Exception $e)
{
return false;
}

Categories