How do I get a log file in Laravel? - php

I have a file full of logs! I called them apache.logs.
So now I need to get them in Laravel and I don't know how.
I just want to save all logs in a variable ($logs) and view them.
public function getlogs ()
{
$logs = \Request::file('apache.log');
return view('logs' , [
'all_logs' => $logs
]);
}
This doesn't work and I don't know what I need to change.

If your using \Request::file then the file should come along with the request params, But here seems like you want to access a stored file in file system using laravel
to do that
ini_set('memory_limit','256M');
$logs = \File::get('apache.log');
return view('logs' , [
'all_logs' => $logs
]);
UPDATE
if you file is in root same like composer.json then you need to change the path to match with it like
ini_set('memory_limit','256M');
$path = base_path()."/apache.log"; //get the apache.log file in root
$logs = \File::get($path);
return view('logs' , [
'all_logs' => $logs
]);
wrap this in a try catch block for best practice, because in some case if apache.log not exists or not accessible laravel trow a exception, we need to handle it
try {
ini_set('memory_limit','256M');
$path = base_path()."/apache.log"; //get the apache.log file in root
$logs = \File::get($path);
return view('logs' , [
'all_logs' => $logs
]);
} catch (Illuminate\Filesystem\FileNotFoundException $exception) {
// handle the exception
}

Related

How to implement Laravel password validation rules as string in arrays?

I want to use the out-of-the-box Laravel password validation rules. This is possible by using the use Illuminate\Validation\Rules\Password class.
So you can use those rules like so:
\Illuminate\Validation\Rule\Password::min(8)->letters()->numbers()->mixedCase()->uncompromised(3)
However, you can't use those rules inside a config file, like in this package because you get the following error when running
artisan config:cache
❯ artisan config:cache > ─╯
Configuration cache cleared successfully.
LogicException
Your configuration files are not serializable.
at vendor/laravel/framework/src/Illuminate/Foundation/Console/ConfigCacheCommand.php:84
80▕ require $configPath;
81▕ } catch (Throwable $e) {
82▕ $this->files->delete($configPath);
83▕
➜ 84▕ throw new LogicException('Your configuration files are not serializable.', 0, $e);
85▕ }
86▕
87▕ $this->info('Configuration cached successfully.');
88▕ }
1 bootstrap/cache/config.php:859
Error::("Call to undefined method Illuminate\Validation\Rules\Password::__set_state()")
After reading the docs, it seems that you can't use those password rules as strings inside an array like so:
"password_rules" => ['min:8'],
So checking the available rules, the rest of the following rules (letters, mixedCase, uncompromised) are not available.
Then, is there a workaround to set those password rules inside the config file?
(so that, I can avoid the LogicException: Your configuration files are not serializable. after executing the artisan config:cache command).
use Illuminate\Validation\Rules\Password;
$rules = [
'password' => [
'required',
'string',
Password::min(8)
->mixedCase()
->numbers()
->symbols()
->uncompromised(),
'confirmed'
],
]
Try using the above code it should work.
I am not a Laravel person, but you can put the config into an array and then unpack it later in your app with something like this:
// for illustration
class Mock {
public function __call($name, $args) {
printf("called: %s(%s)\n", $name, implode(', ', $args));
return $this;
}
// this is awful. never do this.
// in Laravel the min() function, and only this function, is basically
// an alias to the constructor, which is weird.
public static function __callStatic($name, $args) {
return (new self())->$name(...$args);
}
}
$params = [
'min' => [8],
'letters' => [],
'numbers' => [],
'mixedCase' => [],
'uncompromised' => [3]
];
$o = NULL;
foreach( $params as $func => $args ) {
if( is_null($o) ) {
$o = Mock::$func(...$args);
} else {
$o = $o->$func(...$args);
}
}
Output:
called: min(8)
called: letters()
called: numbers()
called: mixedCase()
called: uncompromised(3)

Laravel viewing picture in local disk

I am making like a dropbox clone for a school project, i made an upload fuction that uploads to the local disk so it cant be accessed by everyone.
Upload Function
public function updatedUpload($upload){
$object = $this->currentTeam->objects()->make(['parent_id' => $this->object->id]);
$object->objectable()->associate(
$this->currentTeam->files()->create([
'name' => $upload->getClientOriginalName(),
'size' => $upload->getSize(),
'path' => $upload->storePublicly('files', ['disk' => 'local'])
])
);
$object->save();
$this->object = $this->object->fresh();
}
But I want to put it in an in the home.blade.
How do I make this and only the person who uploaded it can access it?
You can create a specific link for the user that can see this resource.
For example in your routes/web.php
Route::get('/private_resource',[\App\Http\Controllers\PrivateResource::class, 'getLocalResource'])
->name('get_private_resource')->middleware('auth');
Define PrivateResource controller
class PrivateResource
{
public function getLocalResource($filename){
// Get your resource, for example
$file = File::where('name', $filename)->first();
// Check whether user can access this resource
// For example
if(\Auth::id() != $file->user_id) abort(403);
return \Storage::disk('local')->download($filename);
}
}
Extra: If you want extra privacy, you can use signed route using below function.
\URL::signedRoute('get_private_resource');
And add signed middleware to your route
Route::get('/private_resource',[\App\Http\Controllers\PrivateResource::class, 'getLocalResource'])
->name('get_private_resource')->middleware('auth','signed');

Uploading a file via PHP + Symfony 4 throws an "File not found error"

I am trying to upload a file using Symfony 4 documentation (https://symfony.com/doc/4.0/controller/upload_file.html) - yes, I know that is an obsolete version, but at the moment I can't update it.
I have done everything as in documentation (except for creating a new entity, because I only need to upload files, and send link to that file in email), files are uploaded correctly to my directory, but it throws HTTP 500 errors, and in log files there are something like this:
[2020-04-20 15:39:40] request.CRITICAL: Uncaught PHP Exception Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException: "The file "/tmp/phpr2tM6D" does not exist" at [...]/vendor/symfony/http-foundation/File/File.php line 37 {"exception":"[object] (Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException(code: 0): The file \"/tmp/phpr2tM6D\" does not exist at [...]/vendor/symfony/http-foundation/File/File.php:37)"} []
any ideas?
ok, so form is basically just
{{ form_start(warranty_form) }}
{{ form_end(warranty_form)}}
and fragments of controller
$form = $this->createForm(WarrantyType::class);
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()) {
/** #var UploadedFile $documentFile */
$documentFile = $form->get('documentFile')->getData();
if($documentFile) {
$originalDocumentFilename = pathinfo($documentFile->getClientOriginalName(), PATHINFO_FILENAME);
$newDocumentFilename = uniqid().'.'.$documentFile->guessExtension();
try {
$documentFile->move('%kernel.project_dir%/public/uploads/pdf',$newDocumentFilename);
} catch(FileException $e) {
}
$message = (new \Swift_Message('Test email '))
->setFrom('error#example.org')
->setTo('error#example.org')
->setBody("a","text/plain");
}
and form is just a standard form, with possibility to upload PDF files
->add('documentFile', FileType::class, ['label' => 'Dokument', 'mapped' => false, 'required' => true, 'constraints' => [new File(['maxSize' => '1024k', 'mimeTypes' => ['application/pdf', 'application/x-pdf'], 'mimeTypesMessage' => 'Załaduj prawidłowy dokument'])]])
First i would use your try+catch block to output your error details with
} catch(FileException $e) {
dd($e);
}
There could be more information you need to debug.
From your provided error message "The file "/tmp/phpr2tM6D" does not exist" i would suggest to check that after an upload that this file or a similiar is created for "/tmp" AND way more important is that it can be accessed by your PHP Process. I would say the file is there, but it cannot be read by php. This could happen if your webserver and php use different owner/groups.
Can you show whole controller method? Do you use $documentFile variable after move file?
It looks like the catch(FileException $e) should suppress your exception, and as it still appear I think maybe you somewhere try to access $documentFile variable again or maybe tried to call $form->get('documentFile')->getData()?
You should know that $documentFile->move('', ''); is use $renamed = rename($this->getPathname(), $target);
more see

Laravel get path of saved file from upload

I have a laravel upload for file (along with other data that is passed to the database) Everything works. But I just can't figure out how to save the path of the file that is saved.
Here is my controller function:
public function store(Request $request)
{
request()->validate([
'name' => 'required',
'logo' => 'nullable',
'original_filename' => 'nullable',
]);
//This is where the file uploads?
if ($request->hasFile('logo')) {
$request->file('logo')->store('carrier_logo');
$request->merge([
'logo' => '',//TODO: get file location
'original_filename' => $request->file('logo')->getClientOriginalName(),
]);
}
Carrier::create($request->all());
return redirect()->route('carriers.index')->with('toast', 'Carrier created successfully.');
}
The thing I want to achieve:
I want logo to fill with something like carrier_logo/ZbCG0lnDkUiN690KEFpLrNcn2exPTB8mUdFDwAKN.png
The thing that happened every time I tried to fix it was that it placed the temp path in the database. Which ended up being something in the PHP install directory.
Just assign result to variable:
$path = $request->file('logo')->store('carrier_logo');
According to docs
Then you can do with $path variable whatever you want.
just assign the value like this.
$location=base_path('img/'.$filename);
and save it in db.
You could do this:
For FileName
$fileName = $request->file('test')->getClientOriginalName();
OR
$fileName = $request->user()->id.'.'.$request->file('logo')->getClientOriginalExtension();
$imageDirectory = 'logo_images';
$path = $request->file('logo')->storeAs($imageDirectory, $fileName);
dd($path);

Initial migrate in laravel 5 with a reference in the ConfigServerProvider fails

In my ConfigServerProvider.php at boot there is a reference to the configs database table. At initial migrate this database table doesn't exist, so I am getting an error. How can I run the first time 'php artisan migrate', while leaving this boot line intact?
public function boot() {
config([
'version' => "1.0.2",
'title' => Config::where('name', 'title')->first()->pluck('value')
]);
}
I added this around the whole config:
if(Schema::hasTable('configs')) { }
And that seems to make all work.
In my app i made this:
try {
$configs = Config::all();
} catch (\Exception $e) {
$configs = [];
}

Categories