I've been having some trouble validating multiple files and text at same time.
when I validate the whole request $request->all(); the file rules wont work.
'file' => 'required|mimes:png,jpeg,jpg,gif|max:3000'.
That gets fixed if I only validate the files in an array array('file'=> $file), but this way I cant validate the other inputs.
I got the multiple files part from the internet, and added my part for the other inputs, here's my function:
public function createNewPost(Request $request) {
$post = new Post;
$post->user_id = Auth::user()->id;
$post->title = $request->input('title');
$post->body = $request->input('body');
$post->status= "borrador";
$post->save();
$post->img = "/uploads/posts/".$post->id;
$post->save();
$files = Input::file('file');
$file_count = count($files);
$uploadcount = 0;
foreach($files as $file) {
$rules = array(
'file' => 'required|mimes:png,jpeg,jpg,gif|max:3000',
'title' => 'required|unique:posts|max:255',
'body' => 'required'
);
$messages = [
'title.required' => 'Sin titulo?',
'body.required' => 'No has escrito nada',
'file.required' => 'Selecciona al menos 1 imagen.',
'file.mimes' => 'No puedes utilizar ese tipo de imagen, intenta con (jpg/png/jpeg).',
'file.max' => 'El total de imagenes no puede pesar mas de 3MB.'
];
$validator = Validator::make(array('file'=> $file), $rules, $messages);
if($validator->passes()){
$destinationPath = 'uploads/posts/'.$post->id;
//$filename = $file->getClientOriginalName();
$filename = $uploadcount.".".$file->getClientOriginalExtension();
$upload_success = $file->move($destinationPath, $filename);
$uploadcount ++;
}
}
if($uploadcount == $file_count){
Session::flash('success', 'Upload successfully');
return Redirect::to('/admin/post/new');
}
else {
return Redirect::to('/admin/post/new')->withInput()->withErrors($validator);
}
}
Try this, and remove your foreach files loop:
$files = count($this->input('file')) - 1;
foreach(range(0, $files) as $index) {
$rules['file.' . $index] = 'required|mimes:png,jpeg,jpg,gif|max:3000';
}
Source
Related
A few months ago a friend of mine added in my cms created in laravel the upload of images via imgur, only that I would like to remove it, on the cms however the images are saved (locally) I would like to remove the upload on imgur and I would like to stay the images locally
public function imageProfile(Request $request)
{
$user = Auth::user();
$rules = array(
'profile-image' => 'required|image|mimes:jpeg,png,jpg,gif|max:8192|dimensions:min_width=160,min_height=160',
);
$customMessages = [
'profile-image.required' => 'E\' richiesta una immagine per cambiare immagine di profilo.',
'profile-image.image' => 'Devi inserire un immagine valida.',
'profile-image.mimes' => 'L\'immagine inserita non ha un formato adatto.',
'profile-image.dimensions' => 'L\'immagine deve essere minimo 160x160.',
];
$validator = Validator::make(Input::all(), $rules, $customMessages);
if ($validator->fails()) {
return response()->json(['success' => false, 'error' => $this->validationErrorsToString($validator->errors())]);
}
if ($request->hasFile('profile-image')) {
$number = mt_rand(1,1000000);
$image = $request->file('profile-image');
$name = $user->username.'-'.Carbon::now()->toDateString().'-'.$number.'.'.$image->getClientOriginalExtension();
$destinationPath = public_path('/uploads/profile');
$imagePath = $destinationPath. "/". $name;
$image->move($destinationPath, $name);
$image = Imgur::setHeaders([
'headers' => [
'authorization' => 'Client-ID MY CLIENT ID',
'content-type' => 'application/x-www-form-urlencoded',
]
])->setFormParams([
'form_params' => [
'image' => URL::to("/").'/uploads/profile/'. $name,
]
])->upload(URL::to("/").'/uploads/profile/'. $name);
\File::delete('uploads/profile/' .$name);
$user->image_profile = $image->link();
$user->save();
$html = $image->link();
return response()->json(['success' => true, 'html' => $html, 'image' => $image->link()]);
}
}
My server is running Ubuntu 16.04 + Laravel 5.5
Best Regards
This code will only upload photo to your local directory.
public function imageProfile(Request $request)
{
$user = Auth::user();
$rules = array(
'profile-image' => 'required|image|mimes:jpeg,png,jpg,gif|max:8192|dimensions:min_width=160,min_height=160',
);
$customMessages = [
'profile-image.required' => 'E\' richiesta una immagine per cambiare immagine di profilo.',
'profile-image.image' => 'Devi inserire un immagine valida.',
'profile-image.mimes' => 'L\'immagine inserita non ha un formato adatto.',
'profile-image.dimensions' => 'L\'immagine deve essere minimo 160x160.',
];
$validator = Validator::make(Input::all(), $rules, $customMessages);
if ($validator->fails()) {
return response()->json(['success' => false, 'error' => $this->validationErrorsToString($validator->errors())]);
}
if ($request->hasFile('profile-image')) {
$number = mt_rand(1,1000000);
$image = $request->file('profile-image');
$name = $user->username.'-'.Carbon::now()->toDateString().'-'.$number.'.'.$image->getClientOriginalExtension();
$destinationPath = public_path('/uploads/profile');
$imagePath = $destinationPath. "/". $name;
$image->move($destinationPath, $name);
// remove this commented portion
// $image = Imgur::setHeaders([
// 'headers' => [
// 'authorization' => 'Client-ID MY CLIENT ID',
// 'content-type' => 'application/x-www-form-urlencoded',
// ]
// ])->setFormParams([
// 'form_params' => [
// 'image' => URL::to("/").'/uploads/profile/'. $name,
// ]
// ])->upload(URL::to("/").'/uploads/profile/'. $name);
// \File::delete('uploads/profile/' .$name);
// $user->image_profile = $image->link();
// $user->save();
// $html = $image->link();
// update this portion to
$user->image_profile = $imagePath;
$user->save();
$html = $imagePath;
// return response()->json(['success' => true, 'html' => $html, 'image' => $image->link()]);
// also update this portion to
return response()->json(['success' => true, 'html' => $html, 'image' => $imagePath]);
}
}
I am creating a laravel API for complaints. This code is not saving multiple images in the database and I have to show multiple images in JSON response in an array. I am using array_get but it's not working for me. I have tried many things but it is not saving images in database. I have no idea. I am saving images in other table.
public function Complains(Request $request)
{
$response = array();
try {
$allInputs = Input::all();
$userID = trim($request->input('user_id'));
$cordID = trim($request->input('cord_id'));
$phone = trim($request->input('phone'));
$address = trim($request->input('address'));
$description = trim($request->input('description'));
// $image = array_get($allInputs, 'image');
$validation = Validator::make($allInputs, [
'user_id' => 'required',
'cord_id' => 'required',
'phone' => 'required',
'address' => 'required',
'description' => 'required',
]);
if ($validation->fails()) {
$response = (new CustomResponse())->validatemessage($validation->errors()->first());
} else {
$checkRecord = User::where('id', $userID)->get();
if (count($checkRecord) > 0) {
$complainModel = new Complains();
$complainModel->user_id = $userID;
$complainModel->cord_id = $cordID;
$complainModel->phone_no = $phone;
$complainModel->address = $address;
$complainModel->description = $description;
$saveData = $complainModel->save();
if ($saveData) {
if ($request->file('image')) {
$path = 'images/complain_images/';
// return response()->json(['check', 'In for loop']);
foreach ($request->file('image') as $image) {
$imageName = $this->uploadImage($image, $path);
$ImageSave = new ComplainImages();
$ImageSave->complain_id = $complainModel->id;
$ImageSave->image_url = url($path . $imageName);
$ImageSave->save();
}
}
$jsonobj = array(
'id' => $userID,
'name' => $cordID,
'email' => $phone,
'phone' => $address,
'description' => $description,
);
return Response::json([
'Exception' => "",
'status' => 200,
'error' => false,
'message' => "Complain Registered Successfully",
'data' => $jsonobj
]);
}
}else{
$response = (new CustomResponse())->failResponse('Invalid ID!');
}
}
} catch (\Illuminate\Database\QueryException $ex) {
$response = (new CustomResponse())->queryexception($ex);
}
return $response;
}
public function uploadImage($image, $destinationPath)
{
$name = rand() . '.' . $image->getClientOriginalExtension();
$imageSave = $image->move($destinationPath, $name);
return $name;
}
There is a mistake in looping allImages. To save multiple images try below code
foreach($request->file('image') as $image)
{
$imageName = $this->uploadImage($image, $path);
// other code here
}
Check if you are reaching the loop
return response()->json(['check': 'In for loop'])
I have a post with title, texts & image. But I can't save the image path to database. Here is my code.
public function save(Request $request, Post $post)
{
$this->validate(request(),
[
'title' => 'required',
'image' => 'image|mimes:jpg,png,jpeg'
]);
if($request->hasFile('image'))
{
$file = $request->file('image');
$fileNameExt = $request->file('image')->getClientOriginalName();
$fileName = pathinfo($fileNameExt, PATHINFO_FILENAME);
$fileExt = $request->file('image')->getClientOriginalExtension();
$fileNameToStore = $fileName.'_'.time().'.'.$fileExt;
Image::make($file)->resize(600, 600)->save( public_path('media/' . $fileNameToStore));
$post->image = $fileNameToStore;
auth()->user()->publish(
new Post(request(['title', 'text', 'image']))
);
}
return redirect ('/');
}
But it does not store image path to image column of database. Instead tmp data like C:\xampp\tmp\phpC549.tmp stored. What is wrong here?
I think you need to change the save code
auth()->user()->publish(
new Post(request(['title', 'text', 'image']))
);
to
auth()->user()->publish(
new Post([
'title'=>$request->title,
'text'=>$request->text,
])
);
since image val already set inside hasfile if condition
Sample Image path
public function addBlogCategoryPost(BlogCategoryRequest $request) {
$destinationPath = 'iamge path';
$data = [
'category_name' => $request->category_name,
'category_description' => $request->category_description,
'seo_url' => $request->seo_url,
'meta_title' => $request->meta_title,
'meta_description' => $request->meta_description,
'meta_keywords' => $request->meta_keywords,
'meta_author' => $request->meta_author,
];
if ($request->hasFile('category_image')) {
$file = $request->file('category_image');
//move iamge to folder
$fileName = str_random(30) . '.' . $file->clientExtension();
$file->move($destinationPath, $fileName);
$data['category_image'] = $fileName;
}
$addTag = BlogCategory::create($data);
if ($addTag) {
return $addTag;
}
}
I am trying to upload files with Persian name like نام فایل but the file uploads and stores with unknown chars name like تقسیم_وظای٠it really stuck me I don't know what to do.
This is the controller code for uploading the file:
$files = Input::file('files');
$errors = "";
$file_data = array();
if(Input::hasFile('files'))
{
foreach($files as $file)
{
// validating each file.
$rules = array('file' => 'required'); //'required|mimes:png,gif,jpeg,txt,pdf,doc'
$validator = Validator::make(
[
'file' => $file,
'extension' => Str::lower($file->getClientOriginalExtension())
],
[
'file' => 'required',
'extension' => 'required|in:jpg,jpeg,bmp,png,pdf,doc,docx,xls,xlsx,zip'
]
);
if($validator->passes())
{
// path is root/uploads
$destinationPath = 'uploads/docs/';
$filename = $file->getClientOriginalName();
$temp = explode(".", $filename);
$extension = end($temp);
$lastFileId = $object_id;
$lastFileId++;
$filename = $temp[0].'_'.$object_id.'.'.$extension;
$upload_success = $file->move($destinationPath, $filename);
if($upload_success)
{
$data = array(
'file_name' => $filename,
'meeting_id' => $object_id,
'user_id' => Auth::user()->id
);
//call the model function to insert the data into upload table.
meetingModel::uploadFiles($data);
}
else
{
// redirect back with errors.
return Redirect::back()->withErrors($validator);
}
}
else
{
// redirect back with errors.
return Redirect::back()->withErrors($validator);
}
}
}
I'm trying to upload images in Laravel using this code:
public function postAddPictures(Request $request)
{
// getting all of the post data
$files = $request->file('cover_image');
// Making counting of uploaded images
$file_count = count($files);
// start count how many uploaded
$uploadcount = 0;
foreach($files as $file) {
$messages = [
'cover_image.required' => 'U moet een afbeelding opgeven.',
'cover_image.image' => 'De bestanden moeten een afbeelding zijn (jpeg, png, bmp, gif, or svg).',
'description.required' => 'U moet een beschrijving opgeven.'
];
$rules = [
'cover_image' => 'required',//|mimes:png,gif,jpeg,jpg,bpm,svg
'album_id' => 'required|numeric|exists:albums,id',
'description' => 'required'
];
$validate = ['file'=> $file, 'description' => $request->get('description'), 'album_id'=> $request->get('album_id')];
$validator = Validator::make($validate, $rules, $messages);
if ($validator->fails()) {
return Redirect::to('admin/pictures/add')->withInput()->withErrors($validator);
}
$random_name = str_random(8);
$destinationPath = 'public/uploads/pictures/rallypodium/website/'.Album::find($request->get('album_id'))->type.'/'.Album::find($request->get('album_id'))->name.'/';
$extension = $file->getClientOriginalExtension();
$filename = $random_name.'_album_image.'.$extension;
$uploadSuccess = $file->move($destinationPath, $filename);
Images::create([
'description' => $request->get('description'),
'image' => $filename,
'album_id'=> $request->get('album_id')
]);
$uploadcount ++;
}
if($uploadcount == $file_count){
Activity::log('heeft foto's in de map map "'.ucwords(str_replace('-', ' ', Album::find($request->get('album_id'))->name)).'" toegevoegd.');
$request->session()->flash('alert-success', 'Foto's succesvol toegevoegd.');
return Redirect::to('admin/pictures/add');
}
}
The problem here is, it keeps returning the error message 'U moet een afbeelding opgeven.'. It doesn't store the data in the database nor uploads the files.
This are my fields in HTML:
cover_image
album_id
description
Could someone help me out? I tried different ways already but I can't find the solution at all.
Kindest regards,
Robin
Instead of a key 'file' you should use key 'cover_image' if you want to validate all files one by one.
$validate = ['cover_image'=> $file, 'description' => $request->get('description'), 'album_id'=> $request->get('album_id')];