Laravel uploading multiple images doesn't work, also mimes don't - php

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

Related

$directory result Null in codeigniter

I made a file upload in codeigniter, but in the controller I set $ directory = './assets/images/'; unreadable on vmware.
please help, here is my controller
public function tambahfotoproses()
{
$variable = 'foto'; //variable name dari form
$directory = './assets/images/'; //direktori
$allowed_file = 'gif|jpg|jpeg|png|JPG|GIF|PNG|JPEG'; //file yang diizinkan dibatasi dengan tanda
$upload['detail'] = $this->m_admin->uploadfile($variable,$directory,$allowed_file); //proses dengan modul insertfile
var_dump($upload); die();
/* to upload file */
$filename = $upload['detail']['file_name'];
if ($filename != "")
{
$data = array(
'foto' => $filename,
'person_nm' => $this->input->post('person_nm'),
'pengupload' => $this->input->post('pengupload'),
'tgl' => $this->input->post('tgl')
);
$insert = $this->db->insert('eregister_foto',$data);
} else {
$data = array(
'foto' => $filename,
'person_nm' => $this->input->post('person_nm'),
'pengupload' => $this->input->post('pengupload'),
'tgl' => $this->input->post('tgl')
);
$insert = $this->db->insert('eregister_foto',$data);
}
redirect('index.php/admin/foto_dr');
}
I deliberately gave var_dump () to find out the results of $ upload
the result is array (1) {["detail"] => int (0)}
photo not uploaded
and here is my modals.php
/AKSI UPLOAD FILE/
function uploadfile($var,$dir,$all){
$new_name = $this->input->post('person_nm');
$config2=array(
'image_library' => 'gd2',
'upload_path' => $dir."/dokter/", //lokasi gambar akan di simpan
'allowed_types' => $all, //ekstensi gambar yang boleh di unggah
'create_thumb' => TRUE,
'max_size' => '2048', //batas maksimal ukuran gambar
'file_name' => $new_name
);
$this->load->library('upload');
$this->upload->initialize($config2);
if ($this->upload->do_upload($var))
{
return $this->upload->data();
}
else
{
return 0;
}
}
i've try to rewrite folder "dokter" too, and still can't work

Remove imgur from uploading images

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

Laravel uploading file with different charset

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

Laravel 5.2 Validator for text and multiple files

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

Laravel and unique slugs

I'm trying to generate an get unique slugs, just like MyBB does, but it doens't work well...
I'm using the plugin https://github.com/cviebrock/eloquent-sluggable/tree/2.x for Laravel 4.2.
So I got this:
use Cviebrock\EloquentSluggable\SluggableInterface;
use Cviebrock\EloquentSluggable\SluggableTrait;
class ForumController extends \BaseController implements SluggableInterface {
use SluggableTrait;
protected $sluggable = [
'build_from' => 'title',
'save_to' => 'slug',
];
And in that Class, I don't know how I need to generate the slug,
it needs to be generated in this function:
public function PostTopic($cid)
{
//Get all the data and store it inside Store Variable
$data = Input::all();
// Make's messages of faults
$messages = array(
'title.required' => 'U moet een titel opgeven!',
'titel.unique' => 'De opgegeven titel bestaat al, gebruik een andere.',
'message.required' => 'u moet een bericht opgeven!',
'spamprt' => 'honeypot', //spam protection
'time' => 'required|honeytime:60'
);
$rules = array(
'title' => 'required',
'message' => 'required'
);
$validator = Validator::make($data, $rules, $messages);
//process the storage
if ($validator->fails())
{
return Redirect::back()->with('errors', $validator->errors())->withInput();
}else{
//store
$thread = new Thread;
$thread->cid = $cid;
$thread->title = Input::get('title');
$thread->message = Input::get('message');
$thread->prefix = 0;
$thread->uid = Auth::id();
$thread->username = Auth::user()->username;
$thread->date_posted = Carbon\Carbon::now();
$thread->save();
Session::put('_token', sha1(microtime()));
//redirect
return Redirect::back()->with('message', 'Uw bericht is succesvol geplaatst!');
}
}
But how? And how do I need to get the slugs to display them in an URL or so?

Categories