my image are not saved in upload folder in laravel - laravel

whenever I uploaded an image in laravel, the image is upload to the database but after database uploading, my image didn't save that image in my root folder,
here is my upload code:
public function store(Request $request)
{
$records = $request->all();
if ($records != '') {
if ($request->session()->has('is_user_logged')) {
$UserPostModel = new UserPostModel;
$UserPostModel->uid = $request->session()->get('uid');
$UserPostModel->uname = $request->session()->get('name');
$UserPostModel->msg = $request->input('status');
$UserPostModel->eid = $request->input('event');
if ($request->hasFile('image')) {
if ($request->file('image')->isValid()) {
$fileName = $request->file('image')->getClientOriginalName();
$fileName = time() . "_" . $fileName;
$request->file = move_uploaded_file('uploads',$fileName);
$UserPostModel->image = $fileName;
}
}
$UserPostModel->save();
return redirect('uprofile')->with('message', 'Seccessfully Post !');
} else {
return redirect('login');
}
} else {
return redirect('/uprofile')->with('message', 'Please select image!');
}
}

Use store method and pass the driver as the second argument
$path = $request->file('image')->store($store_path, 'public');

Please replace this code with your image upload condition.
if ($file = $request->file('image')) {
$name = time() . $file->getClientOriginalName();
$file->move('uploads', $name);
$UserPostModel->image = $name;
}
$UserPostModel -> save();

Related

Save both original image and conversion to webp in laravel storage

I'm trying to save original jpg image and also a converted webp image to my storage when I'm storing images in my project.
public function store($data)
{
if (!$data->hasFile('fileName')) {
return response()->json(['upload_file_not_found'], 400);
}
$allowedfileExtension = ['jpg', 'jpeg'];
$files = $data->file('fileName');
$errors = [];
$images = [];
foreach ($data->fileName as $mediaFiles) {
$extension = $mediaFiles->getClientOriginalExtension();
$check = in_array($extension, $allowedfileExtension);
if ($check) {
// $path = $mediaFiles->store('public/images');
$name = $mediaFiles->getClientOriginalName();
//store image file into directory and db
$image = new Image();
$image->title = $name;
// $image->path = substr($path, 7);
$image->description = $data->description;
$image->author_id = $data->author_id;
$image->save();
//put image to storage wih unique folder
$path = $mediaFiles->storeAs('public/images/article-images/'.$image->id, $name);
//try to convert to webp and add to storage
$image = InterventionImage::make($mediaFiles)->encode('webp', 90)->resize(200, 250)->save('public/images/' . $name . '.webp');
//
//update images path in database
$image->update(['path' => substr($path, 7)]);
//add to attach the article id
if ($data->article_id) {
$image->articles()->attach($data->article_id);
}
array_push($images, $image);
} else {
return response()->json(['invalid_file_format'], 422);
}
}
return $images;
}
I'm using intervention library but when I try to save converted image to my storage I get the error "message": "Can't write image data to path (public/images/newimage.jpg.webp)",
can someone help with this or have any other suggestion how to do this?
if you want to convert image in to WEBP without any service or package, try this method. work for me. have any question can ask. Thankyou
$post = $request->all();
$file = #$post['file'];
$code = 200;
$extension = $file->getClientOriginalExtension();
$imageName = $file->getClientOriginalName();
$path = 'your_path';
if(!$file->move(public_path($path), $imageName)){
$code = 404;
}
if(in_array($extension,["jpeg","jpg","png"])){
//old image
$webp = public_path().'/'.$path.'/'.$imageName;
$im = imagecreatefromstring(file_get_contents($webp));
imagepalettetotruecolor($im);
// have exact value with WEBP extension
$new_webp = preg_replace('"\.(jpg|jpeg|png|webp)$"', '.webp', $webp);
// set qualityy according to requirement
return imagewebp($im, $new_webp, 50);
}
this will save JPG/PNG and WEBP file both to the move Folder.
If someone ever have the same problem I did it like this
public function newStore($data)
{
if (!$data->hasFile('fileName')) {
return response()->json(['upload_file_not_found'], 400);
}
$allowedfileExtension = ['jpg', 'jpeg'];
$files = $data->file('fileName');
$errors = [];
$images = [];
foreach ($data->fileName as $mediaFiles) {
$extension = $mediaFiles->getClientOriginalExtension();
$check = in_array($extension, $allowedfileExtension);
if ($check) {
// $path = $mediaFiles->store('public/images');
$name = $mediaFiles->getClientOriginalName();
//getting the name of the file without extension
$filename = pathinfo($name, PATHINFO_FILENAME);
//store image file into directory and db
$image = new Image();
$image->title = $name;
// $image->path = substr($path, 7);
$image->description = $data->description;
$image->author_id = $data->author_id;
$image->save();
//put image to storage in unique folder
$path = $mediaFiles->storeAs('public/images/article-images/' . $image->id, $name);
//imege conversion in webp format and move to right folder
$interventionImage = InterventionImage::make($mediaFiles)->stream("webp", 100);
Storage::disk('local')->put($filename . '.webp', $interventionImage, 'public');
Storage::move($filename . '.webp', 'public/images/article-images/' . $image->id . '/' . $filename . '.webp');
//update images path in database
$image->update(['path' => substr($path, 7)]);
//add to attach the article id
if ($data->article_id) {
$image->articles()->attach($data->article_id);
}
array_push($images, $image);
} else {
return response()->json(['invalid_file_format'], 422);
}
}
return $images;
}
and my folder structure looks like this:

I get this error when trying to verify the email of candidates, Array to String conversion

I have a laravel system that when someone registers, they get a link on their emails where they have to click on it to verify their email. Once they click the link, their information is stored in the users table and the candidates table.
However, values are only inserted in the users table and not the candidates table, and I get the error "Array to string conversion".
Also, the link works well in local host but not after hosting the system.
RegisiterController.php
Str.php`
public function registerCandidate(Request $request){
if(setting('general_enable_candidate_registration')!=1){
return abort(401);
}
$rules = [
'first_name'=>'required',
'last_name'=>'required',
'national_id'=>'required',
'gender'=>'required',
'email'=>'required|email|string|max:255|unique:users',
'date_of_birth_year'=>'required',
'date_of_birth_month'=>'required',
'date_of_birth_day'=>'required',
'categories'=>'required',
'picture' => 'nullable|max:'.config('app.upload_size').'|mimes:jpeg,png,gif',
'cv_path' => 'nullable|max:'.config('app.upload_size').'|mimes:'.config('app.upload_files'),
];
if(setting('general_candidate_captcha')==1){
$rules['captcha'] = 'required|captcha';
}
foreach(CandidateFieldGroup::where('registration',1)->orderBy('sort_order')->get() as $group){
foreach($group->candidateFields as $field){
if($field->type=='file'){
$required = '';
if($field->required==1){
$required = 'required|';
}
$rules['field_'.$field->id] = 'nullable|'.$required.'max:'.config('app.upload_size').'|mimes:'.config('app.upload_files');
}
elseif($field->required==1){
$rules['field_'.$field->id] = 'required';
}
}
}
$this->validate($request,$rules);
$requestData = $request->all();
$password= $request->password;
$requestData['name']= $request->first_name.' '.$request->last_name;
$requestData['display_name'] = $request->first_name;
$requestData['password'] = Hash::make($password);
$requestData['role_id'] = 3;
$fields = CandidateField::get();
//check if email verification is required
if(setting('general_candidate_verification')==1){
do{
$hash = Str::random(30);
}while(PendingUser::where('hash',$hash)->first());
$formData = $_POST;
$formData['name'] = $request->first_name.' '.$request->last_name;
$formData['display_name'] = $request->first_name;
$formData['role_id'] = 3;
if($request->hasFile('picture')) {
$path = $request->file('picture')->store(PENDING_USER_FILES,'public_uploads');
$file = UPLOAD_PATH.'/'.$path;
$img = Image::make($file);
$img->resize(500, null, function ($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
});
$img->save($file);
$formData['picture'] = $file;
}
else{
$formData['picture'] =null;
}
if($request->hasFile('cv_path')) {
//$path = $request->file('cv_path')->store(CANDIDATES,'public_uploads');
$name = $_FILES['cv_path']['name'];
$extension = $request->cv_path->extension();
// dd($extension);
$name = str_ireplace('.'.$extension,'',$name);
$name = uniqid().'_'.time().'_'.safeUrl($name).'.'.$extension;
$path = $request->file('cv_path')->storeAs(PENDING_USER_FILES,$name,'public_uploads');
$file = UPLOAD_PATH.'/'.$path;
$formData['cv_path'] = $file;
}
else{
$formData['cv_path'] =null;
}
$pendingUser = PendingUser::create([
'role_id'=>3,
'data'=> serialize($formData),
'hash'=> $hash
]);
//scan for files
foreach($fields as $field){
if(isset($requestData['field_'.$field->id]) && $field->type=='file' && $request->hasFile('field_'.$field->id))
{
//generate name for file
$name = $_FILES['field_'.$field->id]['name'];
//dd($name);
$extension = $request->{'field_'.$field->id}->extension();
// dd($extension);
$name = str_ireplace('.'.$extension,'',$name);
$name = $pendingUser->id.'_'.time().'_'.safeUrl($name).'.'.$extension;
$path = $request->file('field_'.$field->id)->storeAs(PENDING_USER_FILES,$name,'public_uploads');
$file = UPLOAD_PATH.'/'.$path;
$pendingUser->pendingUserFiles()->create([
'file_name'=>$_FILES['field_'.$field->id]['name'],
'file_path'=>$file,
'field_id'=>$field->id
]);
}
}
//send email to user
$link = route('confirm.candidate',['hash'=>$hash]);
$this->sendEmail($request->email,__('site.confirm-your-email'),__('site.confirm-email-mail',['link'=>$link]));
return redirect()->route('register.confirm');
}
//First create user
$user= User::create($requestData);
//Calculate date of birth
$dateOfBirth = $request->date_of_birth_year.'-'.$request->date_of_birth_month.'-'.$request->date_of_birth_day;
$requestData['date_of_birth'] = $dateOfBirth;
//checkfor picture
if($request->hasFile('picture')) {
$path = $request->file('picture')->store(CANDIDATES,'public_uploads');
$file = UPLOAD_PATH.'/'.$path;
$img = Image::make($file);
$img->resize(500, null, function ($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
});
$img->save($file);
$requestData['picture'] = $file;
}
else{
$requestData['picture'] =null;
}
if($request->hasFile('cv_path')) {
//$path = $request->file('cv_path')->store(CANDIDATES,'public_uploads');
$name = $_FILES['cv_path']['name'];
$extension = $request->cv_path->extension();
// dd($extension);
$name = str_ireplace('.'.$extension,'',$name);
$name = $user->id.'_'.time().'_'.safeUrl($name).'.'.$extension;
$path = $request->file('cv_path')->storeAs(CANDIDATE_FILES,$name,'public_uploads');
$file = UPLOAD_PATH.'/'.$path;
$requestData['cv_path'] = $file;
}
else{
$requestData['cv_path'] =null;
}
$user->candidate()->create($requestData);
//save categories
$user->candidate->categories()->attach($request->categories);
//now save custom fields
$customValues = [];
//attach custom values
foreach($fields as $field){
if(isset($requestData['field_'.$field->id]))
{
if($field->type=='file'){
if($request->hasFile('field_'.$field->id)){
//generate name for file
$name = $_FILES['field_'.$field->id]['name'];
$extension = $request->{'field_'.$field->id}->extension();
$name = str_ireplace('.'.$extension,'',$name);
$name = $user->id.'_'.time().'_'.safeUrl($name).'.'.$extension;
$path = $request->file('field_'.$field->id)->storeAs(CANDIDATE_FILES,$name,'public_uploads');
$file = UPLOAD_PATH.'/'.$path;
$customValues[$field->id] = ['value'=>$file];
}
}
else{
$customValues[$field->id] = ['value'=>$requestData['field_'.$field->id]];
}
}
}
$user->candidateFields()->sync($customValues);
$message = __('mails.new-account',[
'siteName'=>setting('general_site_name'),
'email'=>$requestData['email'],
'password'=>$password,
'link'=> url('/login')
]);
$subject = __('mails.new-account-subj',[
'siteName'=>setting('general_site_name')
]);
$this->sendEmail($requestData['email'],$subject,$message);
//now login user
Auth::login($user, true);
//redirect to relevant page
if(session()->exists('candidate_destination')){
$url = session()->get('candidate_destination');
session()->remove('candidate_destination');
return redirect($url);
}
else{
return redirect()->route('home');
}
}
public function confirmCandidate($hash){
//get pending user
$pendingUser = PendingUser::where('hash',$hash)->first();
if(!$pendingUser){
abort(404);
}
$requestData = unserialize($pendingUser->data);
$password = $requestData['password'];
$requestData['password'] = Hash::make($password);
//check for profile picture and move to new directory
if(!empty($requestData['picture']) && file_exists($requestData['picture'])){
$file = basename($requestData['picture']);
$newPath = UPLOAD_PATH.'/'.CANDIDATES.'/'.$file;
rename($requestData['picture'],$newPath);
$requestData['picture'] = $newPath;
}
if(!empty($requestData['cv_path']) && file_exists($requestData['cv_path'])){
$file = basename($requestData['cv_path']);
$newPath = UPLOAD_PATH.'/'.CANDIDATE_FILES.'/'.$file;
rename($requestData['cv_path'],$newPath);
$requestData['cv_path'] = $newPath;
}
//First create user
$user= User::create($requestData);
//Calculate date of birth
$dateOfBirth = $requestData['date_of_birth_year'].'-'.$requestData['date_of_birth_month'].'-'.$requestData['date_of_birth_day'];
$requestData['date_of_birth'] = $dateOfBirth;
$user->candidate()->create($requestData);
//save categories
if(isset($requestData['categories'])){
$user->candidate->categories()->attach($requestData['categories']);
}
$fields = CandidateField::get();
$customValues = [];
//attach custom values
foreach($fields as $field){
if($field->type=='file'){
$pendingFile = $pendingUser->pendingUserFiles()->where('field_id',$field->id)->first();
if($pendingFile){
//generate name for file
$name = $pendingFile->file_name;
$info = new \SplFileInfo($name);
$extension = $info->getExtension();
$name = str_ireplace('.'.$extension,'',$name);
$name = $user->id.'_'.time().'_'.safeUrl($name).'.'.$extension;
$file = UPLOAD_PATH.'/'.CANDIDATE_FILES.'/'.$name;
rename($pendingFile->file_path,$file);
$customValues[$field->id] = ['value'=>$file];
}
}
elseif(isset($requestData['field_'.$field->id])){
$customValues[$field->id] = ['value'=>$requestData['field_'.$field->id]];
}
}
$user->candidateFields()->sync($customValues);
$pendingUser->delete();
$message = __('mails.new-account',[
'siteName'=>setting('general_site_name'),
'email'=>$requestData['email'],
'password'=>$password,
'link'=> url('/login')
]);
$subject = __('mails.new-account-subj',[
'siteName'=>setting('general_site_name')
]);
$this->sendEmail($requestData['email'],$subject,$message);
//now login user
Auth::login($user, true);
//redirect to relevant page
if(session()->exists('candidate_destination')){
$url = session()->get('candidate_destination');
session()->remove('candidate_destination');
return redirect($url);
}
else{
return redirect()->route('home');
}
}
`

Correctly upload an image to database. Laravel vue.js

I'm trying to upload an image to the database but no matter what I try I either get this error
Call to a member function getClientOriginalExtension() on null
or it says it saved correctly but it doesn't save anything
The following code is in the vue.js file in the submit function for the form where this the image is being uploaded. This is what I've tried to send the file to the controller
This gives me the error above
if (this.form.file && this.form.imageUrl) {
this.form.file = this.form.imageUrl;
} else {
}
var data = Converter.objectToFormData(this.form);
this.$refs.form.validate((valid) => {
if (valid) {
this.loading = true;
if (!this.form.id) {
//send code
} else {
//send updated
}
}
This also gives me the error above
let data = Object.assign({}, this.form);
this.$refs.form.validate((valid) => {
if (valid) {
this.loading = true;
if (!this.form.id) {
//send code
} else {
//send updated
}
}
This doesn't give me any errors, but nothing gets saved
var data = new FormData();
data.append('question', this.form.question);
data.append('instruction', this.form.instruction);
data.append('survey_section_id', this.form.survey_section_id);
data.append('response_type_id', this.form.response_type_id);
data.append('questionOptions', this.form.questionOptions);
data.append('rank', this.form.rank);
data.append('num', this.form.num);
data.append('show_text', this.form.show_text);
data.append('file', this.form.file);
this.$refs.form.validate((valid) => {
if (valid) {
this.loading = true;
if (!this.form.id) {
//send code
} else {
//send updated
}
}
This is the code in the controller where the error gets triggered
$destino = 'img/questions';
$image = $request->has('file');
if ($image) {
$imageFile = $request->file('file');
$filename = Uuid::generate(4)->string . '.' . $imageFile->getClientOriginalExtension();
$imageFile->move($destino, $filename);
$preg->image = $destino . '/' . $filename;
}
if I dd($imageFile) it always returns null or false, my guess is that the file isn't being sent as a file but I'm not sure what I'm doing wrong or why this is happening, the $image returns true so it does go into that if statement.
Assuming you have put enctype="multipart/form-data" on your form, there was an error in a laravel 6 that forced me to do this before getting the image:
$destino = 'img/questions';
$image = $request->has('file');
if ($image) {
$size = $request->file('file')->getSize();
$imageFile = $request->file('file');
$filename = Uuid::generate(4)->string . '.' . $imageFile->getClientOriginalExtension();
$imageFile->move($destino, $filename);
$preg->image = $destino . '/' . $filename;
}
I'm not sure if it gave me the same error, but the file was always null if you didn't get the size before,
Hope it helps!

Problem uploading images with Axios and Laravel

I'm trying to upload and save images with Axios and a Laravel API, but i'm getting a 422 error.
I've tested with Postman and i have the same result, i have a similar controller**(without the Foreach)** but to upload only one image at once and it works fine.
///Axios
async submitFiles(){
let fd = new FormData()
for(var i = 0; i < this.files.length; i++){
let file = this.files[i]
fd.append('photo[' + i + ']', file)
}
try{
await this.$axios.$post(`/albums/${this.$route.params.id}/photos`, fd, {headers:{'Content-Type': 'multipart/form-data'}})
console.log(...fd)
alert('uploaded')
this.files = []
}
catch(err){
console.log(err)
alert(err)
}
}
//Laravel
class PhotosInAlbumController extends Controller
{
public function store(PhotoInAlbumRequest $request, Album $album)
{
if($request->hasfile('photo'))
{
$photo = new PhotoInAlbum();
$photo->photo = $request->photo;
$images[] = $request->file('photo');
foreach ($images as $image)
{
$filenameWithExt = $image->getClientOriginalName();
$filename = pathInfo($filenameWithExt, PATHINFO_FILENAME);
$extension = $image->getClientOriginalExtension();
$filenameToStore = $filename.'_'.time().'.'.$extension;
$path = $image->storeAs('photo/images', $filenameToStore,'public');
$photo->photo = $path;
$album->photos()->save($photo);
}
}
return $photo;
}
}
Hope someone can help me to figure out what's going on.
Thanks in advance (=
First, sorry I can't comment yet. But I see in this line:
$images[] = $request->file('photo');
that a bi-dimensional array is built. I would try the assignment without the brackets:
$images = $request->file('photo');

Image source not readable-Laravel 5.8

I am trying to post an image to my front end page but when I click the post button I get an error
Image source not readable
private function handleRequest($request)
{
$data = $request->all();
if ($request->hasFile('image'))
{
$image = $request->file('image');
$fileName = $image->getClientOriginalName();
$destination = $this->uploadPath;
$successUploaded = $image->move(public_path('img'.$fileName));
//$successUploaded = $image->move($destination, $fileName);
if ($successUploaded)
{
$extension = $image->getClientOriginalExtension();
$thumbnail = str_replace(".{$extension}", "_thumb.{$extension}", $fileName);
Image::make($destination . '/' . $fileName)
->resize(250, 170)
->save($destination . '/' . $thumbnail);
}
$data['image'] = $fileName;
}
return $data;
}

Resources