Getting users' email - Laravel 5 PHP - php

I'm attempting to store the email address of any user who uploads a file into an "uploader_name" string variable. I've attempted using the following code whichout success - attempting to upload the file will result in a Class 'App\Http\Controllers\Auth' not found error message being thrown back. I know this is a pretty basic question, but I can't seem to find any answers which specifically work with Laravel 5.
This is what I'm trying to use currently without success.
$filelist->uploader_name = Auth::user()->email;
If it helps, here's the full function which saves some of the automatic information of the file.
public function store()
{
$filelist = new Filelist($this->request->all());
//store file details - thanks to Jason Day on the unit forum for helping with some of this
$filelist->name = $this->request->file('asset')->getClientOriginalName();
$filelist->file_type = $this->request->file('asset')->getClientOriginalExtension();
$filelist->file_size = filesize($this->request->file('asset'));
$filelist->uploader_name = Auth::user()->email;
$filelist->save();
// Save uploaded file
if ($this->request->hasFile('asset') && $this->request->file('asset')->isValid()) {
$destinationPath = public_path() . '/assets/';
$fileName = $filelist->id . '.' . $this->request->file('asset')->guessClientExtension();
$this->request->file('asset')->move($destinationPath, $fileName);
}
return redirect('filelists');
}

You get not found error, because you don't use the right namespace.
You can resolve this if you use the use keyword like this:
use Auth;
public uploadController {
...
}
Or you can use the full namespace:
$filelist->uploader_name = \Auth::user()->email;

You are getting Class 'App\Http\Controllers\Auth' not found error because you are not using the correct namespace:
There are two ways to resolve this:
By including use keyword in your controller
Example:
use Auth;
UploadController{
....
}
or by specifying the full namespace directly like so
$filelist->uploader_name = \Auth::user()->email;

Related

PHP - How to pass class to another class method

Im trying to pass the verot image editing class to a custom class that I created, but it doesnt seem to work, it doesnt do anything when I try to run it. How do I pass the verot image class to my class?
//Edit.php
//Now I run my class
$process = new ProcessEventLogo();
$process->editEventLogo($event_id,$file_ext,$savepath,new upload(''));
Here is my custom class. I thought by running upload('') to this method, Im passing a copy of the verot upload class that I can access in my custom class method. But when I run it, it doesnt even get past the $mainimg->uploaded path. In fact $mainimg = $fileupload->upload($savefile); returns NULL when I var_dump it. What am I doing wrong?
class ProcessEventLogo {
public function editEventLogo($eventid,$fext,$url,$savepath,$fileupload)
{
//We generate the file name to save this image to
$savefile = $savepath .'event_' .$eventid .'.' .$fext;
//We check to see if the event image is there
$mainimg = $fileupload->upload($savefile);
//We now resize the image
if($mainimg->uploaded)
{
$mainimg->file_overwrite = TRUE;
$mainimg->image_ratio_crop = TRUE;
$mainimg->image_resize = TRUE;
$mainimg->image_x = 50;
$mainimg->image_y = 50;
$mainimg->process($savefile);
if($mainimg->processed)
{
echo $mainimg->error;
}
}
}
It appears this worked, can someone verify this is the proper way of doing this? So instead of this line:
//We check to see if the event image is there
$mainimg = $fileupload->upload($savefile);
This worked.
//We check to see if the event image is there
$mainimg = new $fileupload($savefile);
#mr.void Right, so how else would I pass this class to my custom class
method? Just seems like this is the wrong way
I think writing a little Factory is the right way for this:
class uploadFac {
public function getUploadInstance($file)
{
return new upload($file)
}
}
And use it like this:
$uplFac = new uploadFac();
$process = new ProcessEventLogo();
$process->editEventLogo($event_id,$file_ext,$savepath,$uplFac);
and in the method:
public function editEventLogo($eventid,$fext,$url,$savepath,$uplFac)
{
//We generate the file name to save this image to
$savefile = $savepath .'event_' .$eventid .'.' .$fext;
$mainimg = $uplFac->getUploadInstance($savefile);

Cannot declare class App\Utils\System\Log because the name is already in use

I'm using Laravel 5.2 & PHP Version 5.6.21 and have come across the issue :
FatalErrorException in Log.php line 8: Cannot declare class
App\Utils\System\Log because the name is already in use
in Log.php line 8
My Log.php looks like this :
<?php namespace App\Utils\System;
use Log;
use App\Log as LogDB;
use Carbon\Carbon as Carbon;
class Log
{
public function save($msg,$flag)
{
/*
//check to see if there is an organisation set
$org = '';
if(!is_null(session('organisation_name')))
{
$org = session('organisation_name');
}
$message ='{"action":"'.$msg.'", "uuid":"'.\Auth::user()->id.'", "company_id":"'.\Auth::user()->company_id.'","Organisation":"'.$org.'","Date":"'.Carbon::now().'"}';
//set a local log
if($flag=='info')
Log::info($message);
//save to the DB
$l = new LogDB();
$l->log_message = $message;
$l->save();
*/
}
}
The problem, I'm finding is, If I rename log to anything else, I always get the error...
Has anyone had this issue? Any fixes known.
Thanks

Image is saving as tmp file in database laravel

Before explaining the problem. Let me show the controller function:
public function storePost(IdeaRequest $request)
{
$idea = new Idea();
$idea->idea_title = $request->input('idea_title');
$idea->user_id = $request->input('user_id');
$idea->idea_image = $request->file('idea_image')->move('publicPages\images')->getClientOriginalName();
$idea->idea_info = $request->input('idea_info');
$idea->selection = $request->input('selection');
$idea->idea_location = $request->input('idea_location');
$idea->idea_goal = $request->input('idea_goal');
$idea->idea_description = $request->input('idea_description');
$idea->save();
session()->flash('flash_message', 'Your idea has been submitted for Review');
return back();
}
It stores the image as .tmp file. Things I have tried out
guessExtension(), It just returns the extension name and does not
even store the image.
getClientOriginalName(), it throws an error;
getClientOriginalName method is not defined. I have searched the
method and it is in there. used its namespace
Symfony\Component\HttpFoundation\File\UploadedFile. it did not work
either.
Tried different things out from stackoverflow, Nothing has worked
for me till now. In other words, i have invested a lot of time to
solve this problem but nothing worked. Any help would highly be
appreciated.
Here you go:
public function storePost(IdeaRequest $request)
{
$request->file('idea_image')->move('publicPages\images');
$filename = $request->file('idea_image')->getClientOriginalName();
$idea = new Idea();
$idea->idea_title = $request->input('idea_title');
$idea->user_id = $request->input('user_id');
$idea->idea_image = $filename;
$idea->idea_info = $request->input('idea_info');
$idea->selection = $request->input('selection');
$idea->idea_location = $request->input('idea_location');
$idea->idea_goal = $request->input('idea_goal');
$idea->idea_description = $request->input('idea_description');
$idea->save();
session()->flash('flash_message', 'Your idea has been submitted for Review');
return back();
}
Observe closely. You will have to do this in 2 separate lines:
$request->file('idea_image')->move('publicPages\images');
$filename = $request->file('idea_image')->getClientOriginalName();
Why?
move() returns a File object representing the new file.
The File class doesn't have a getClientOriginalName() method. That method belongs to UploadedFile.
When you chain them, you are trying to access getClientOriginalName() from File, which doesn't exist. Have a look at the docs here.
However...
File extends the PHP native SplFileInfo class which has a getFilename() method. So I guess you could also do:
$request->file('idea_image')->move('publicPages\images')->getFilename();

Input class not found in laravel 5

I want to save file uploaded through form into a json file for this I need to get post data which is easily get through Request or Input class methods.
The problem is whenever I use Request or Input I can't get methods such as getClientOriginalName to get name of file and other parameters of file.
My FileController code is as below:
<?php namespace App\Http\Controllers;
use App\Http\Requests;
use Illuminate\Http\Request; // this handles both for Input and Request as in laravel 5.1 documentation
use Illuminate\Support\Facades\Input; // though added some classes to get work
use Illuminate\Support\Facades\File; // though added some classes to get work
use Illuminate\Filesystem\Filesystem; // though added some classes to get work
class FileController extends Controller
{
public function index()
{
$files = $this->getAllData();
return view('document.index', compact('files'));
}
public function create()
{
return view('document.create');
}
public function store(Request $request)
{
$name = $request->input('title');
echo $name;
$file = $request->file('afile');
if($request->hasFile('afile')) {
$file = $request->file('afile');
print_r($file); // return array of uploaded as expected
$filename = $file->getClientOriginalName(); // not working
// or
$filename = Input::file('afile')->getClientOriginalName(); // not working
echo $filename;
}
// print_r($file);
// $data= array('title'=>$name, 'afile'=>$file);
// $this->create_entry($data);
// return redirect('document');
}
}
FYI my file upload is sucessful and has got file array as
Array ( [0] => Symfony\Component\HttpFoundation\File\UploadedFile Object ( [test:Symfony\Component\HttpFoundation\File\UploadedFile:private] => [originalName:Symfony\Component\HttpFoundation\File\UploadedFile:private] => new_file_1.txt [mimeType:Symfony\Component\HttpFoundation\File\UploadedFile:private] => text/plain [size:Symfony\Component\HttpFoundation\File\UploadedFile:private] => 0 [error:Symfony\Component\HttpFoundation\File\UploadedFile:private] => 0 [pathName:SplFileInfo:private] => E:\xampp\tmp\php5680.tmp [fileName:SplFileInfo:private] => php5680.tmp ) )
The only problem is I can't get methods of Symphon2 API though i used
use Input;
or
use Illuminate\Support\Facades\Input;
Every methods of Input are not working either to check its valid or not.
Every tutorial I refer or documentation from laravel 5 uses same as I have used in my code.
So any Kind of suggestion or solution is really appreciated.
the functions as used in this documentation are working but no other methods except than that.
Your missing the use statement for the Input facade. Add the following to your use statements.
use Illuminate\Support\Facades\Input;
You may try this:
$filename = $file->getClientOriginalName();
Since you have already used the following:
$file = $request->file('afile');
The file method returns an instance of Symfony\Component\HttpFoundation\File\UploadedFile and in this case, the instance is already cached in the $file variable.
Also to make sure the upload was successful you may check it using something like this:
if($request->hasFile('afile')) {
$file = $request->file('afile');
$filename = $file->getClientOriginalName() .'.'. $file->getExtension();
}
this works for me
\Input::file('file')->getClientOriginalName();
In your form open tag add 'files' => true
{!! Form::open(array('files' => true, ....)) !!}
In the controller check first if the file has been uploaded correctly
if (!Input::file('afile')->isValid())
{
// return error 50x
}
$filename = Input::file('afile')->getClientOriginalName();
can't apply method to non-object means that Input::file(...) returned null and therefore the file wasn't uploaded or it doesn't exists. Then, when you call ->getClientOriginalName() from a null value php throws an exception.

How can I access my class properties from a namespace with php version 5.5.12?

I'm using WAMPSERVER 2.5 and PHP version 5.5.12 on Windows 8 PC. I created a namespace which worked ok when I was running PHP version 5.2.12. After upgrading to php version 5.5.12 I'm getting error message about undefined variables which I think means that the namespace is not being used. Here's what my code looks like:
In my UploadFile.php file I have this:
<?php
namespace myNamespace;
class UploadFile
{
protected $avatarUrl;
public function getUrl()
{
return $this->avatarUrl;
}
protected function moveFile($file)
{
$filename = isset($this->newName) ? $this->newName : $file['name'];
echo $file[$key];
$success = move_uploaded_file($file['tmp_name'], $this->destination . $filename);
if ($success) {
$url='http://westcoastchill.com/dc-esports/images/' . $filename;
$this->avatarUrl=$url;
...
}
.....
?>
Then here's the html form that uses the class in the namespace where I get the error messages that states that the variable 'newUrl' is undefined and the index 'displaymax' is undifined.
<?php
require_once 'uploads/src/myNamespace/UploadFile.php';//<------names here
if (!isset($_SESSION['maxfiles'])) {
$_SESSION['maxfiles'] = ini_get('max_file_uploads');
$_SESSION['postmax'] = UploadFile::convertToBytes(ini_get('post_max_size'));
$_SESSION['displaymax'] = UploadFile::convertFromBytes($_SESSION['postmax']); //<------ undifined index
}
$max = 50 * 1024;
$result = array();
if (isset($_POST['upload'])) {
$destination = __DIR__ . '/uploads/uploaded/';
try {
$upload = new UploadFile($destination);
$upload->setMaxSize($max);
$upload->allowAllTypes();
$upload->upload();
$result = $upload->getMessages();
$newUrl=$upload->getUrl(); //<----------- here's the undifined newUrl;
} catch (Exception $e) {
$result[] = $e->getMessage();
}
}
$error = error_get_last();
$oldUrl=$newUrl;
...
?>
}
How can I access my class from a namespace with php version 5.5.12?
Thanks for any help with this!
UPDATE: Sorry I had getUrl() outside of superclass but in my actual project is in the correct place. So I tried:
\myNamespace\UploadFile::convertToBytes(ini_get('post_max_size'));...
but I still get the same error. I also tried adding use:
myNamespace\UploadFile and \myNamespace\UploadFile...
still getting the same error message. The thing is my code worked with the using statement before I updated PHP so I'm curious why just an update would change things.
UploadFile class is within the namespace myNamespace, so to reference the class from outside of myNamespace, you would need to use \myNamespace\UploadFile.
If you are already in the global namespace, you don't need the leading slash, but I think it's good practice to always use the leading slash, since the leading slash refers to the global namespace.
Ex:
$_SESSION['postmax'] = \myNamespace\UploadFile::convertToBytes(ini_get('post_max_size'));
and
$upload = new \myNamespace\UploadFile($destination);
The issue was the configuration of the php.ini file. After researching more I tried turning off 'display_errors=Off in the php.ini file and the code the code ran using the namespace and everything. Conclusion: the php.ini file of the new installation different settings. I'll explore the settings more but my problem was solved by turning off error displaying. Obviously this is not a desired option so I'll toggle on and off as I go forward and read up on other parameters in the file that may help me.

Categories