Laravel uploading file with different charset - php

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

Related

How to upload a file in the host with storage?

I wanted to ask what is it like to upload to a host and save it? Of course in the storage folder
Why does this source of mine upload in localhost but not in Host?
But it does not upload at all in the host.
public function store(Request $request)
{
$path = $request->file('image') ?? null;
if ($request->hasFile('image'))
{
$file = $request->file('image');
$name = time();
$extension = $file->getClientOriginalExtension();
$fileName = $name . '.' . $extension;
$path = $file->storeAs('images/aboutExhibitions', $fileName, 'public');
}
AboutExhibition::query()->create([
'user_id' => auth()->id(),
'title' => $request->title,
'link' => $request->link,
'image' => $path,
'options' => $request->options,
'body' => $request->body,
]);
return redirect()->route('admin.aboutExhibitions.index');
}
In the meantime, when I was inside the localhost, I executed the following command before.
php artisan storage:link
Hope this will work.
$image = $request->image;
$image_name=uniqid().date('dmYhis');
$ext=strtolower($image->getClientOriginalExtension());
$image_full_name=$image_name.'.'.$ext;
$image_url=$upload_path.$image_full_name;
$success=$image->move($upload_path,$image_full_name);
$data = array();
$data['image']=$image_url;
$store = Custom::create($data);

How to get multiple images in laravel api?

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

Laravel - Data not stored on database, image upload failed

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

File name change to xxxx.tmp when update file upload Laravel 5.2

Hello I got an error when i tried to update image file. I have 2 form (create and edit). When I create an user with image upload it success and store with right file name to public path and database (filename.jpg).
But when I tried to update, image file success upload to public path with right file name (filename.jpg) but file name that insert to database becomes D:/Xampp/tmp/xxxx.tmp. Can anybody help me? I'm stuck from yesterday.
Create method:
public function store(CreateDosenRequest $request)
{
$user = User::create([
'name' => $request->input('name'),
'username' => $request->input('username'),
'email' => $request->input('email'),
'password' => $request->input('password'),
'admin' => $request->input('admin'),
]);
if (Input::hasFile('fotodosen')) {
$data = Input::file('fotodosen');
$photo = Input::file('fotodosen')->getClientOriginalName();
$fileName = rand(11111, 99999) . '.' . $photo;
$destination = public_path() . '/uploads/';
Request::file('fotodosen')->move($destination, $fileName);
$data = $fileName;
}
$dosen = Dosen::create([
'iddosen' => $request->input('iddosen'),
'nipy' => $request->input('nipy'),
'namadosen' => $user->name,
'user_id' => $user->id,
'alamatdosen' => $request->input('alamatdosen'),
'notelpdosen' => $request->input('notelpdosen'),
'tempatlahirdosen' => $request->input('tempatlahirdosen'),
'tanggallahirdosen' => $request->input('tanggallahirdosen'),
'agamadosen' => $request->input('agamadosen'),
'fotodosen' => $data, //you have to add it hear
]);
return redirect('admin/dosen')->with('message', 'Data berhasil ditambahkan!');
}
Edit method:
public function update($id)
{
if (Input::file('fotodosen')) {
$data = Input::file('fotodosen');
$filename = Input::file('fotodosen')->getClientOriginalName();
$destination = public_path() . '/uploads/';
Request::file('fotodosen')->move($destination, $filename);
$data = $filename;
}
$dosenUpdate = Request::only(['nipy', 'namadosen', 'alamatdosen', 'notelpdosen', 'tempatlahirdosen', 'tanggallahirdosen', 'statusdosen', 'fotodosen']);
$user = User::find($id);
$user->dosen()->update($dosenUpdate);
if(Auth::user()->admin==1) {
return redirect('/admin/dosen')->with('message', 'Data berhasil diubah!');
}
return redirect('/dosen')->with('message', 'Data berhasil diubah!');
}

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

Categories