Laravel - Load a JSON file from /resources folder for API - php

Within a Laravel project, I have an API that is powered by a flat JSON file. I'd like to use the JSON file where it currently resides, which is inside the /resources/modules/ folder in project. Problem is I'm having trouble targeting this location with the Storage:: method. Currently I have the file located in storage/app/public, which works fine with the code below, but ideally I'd reference the /resources/modules/ file.
$this->json_path = Storage::disk('public')->get('file.json');
$this->config_decoded = json_decode($this->json_path, true);
How do I do this using the Storage:: method?

Unless you've updated your public disk to point to the resources/modules directory, this is to be expected. By default, the public disk points to your storage/app/public directory.
You can either set up a new disk in your config/filesystems.php file by adding the something like the following to the disks array:
'modules' => [
'driver' => 'local',
'root' => resource_path('modules'),
'throw' => false,
],
Then your code would be:
$this->json_path = Storage::disk('modules')->get('file.json');
$this->config_decoded = json_decode($this->json_path, true);
Alternatively, you could use the File facade instead:
use Illuminate\Support\Facades\File;
$this->json_path = File::get(resource_path('modules/bob.json'))

Related

Laravel response 404 file not found

I'm using Dingo/API and this is a transformer that returns me data
return [
'id' => $site->id,
'path' => asset($site->path),
'siteLink' => $site->site_link,
'features' => $features,
];
Generated link looks good, however when I try to access it from my Angular app it's said that
Failed to load resource: the server responded with a status of 404 (Not Found)
http://api.example.com/public/thumbnails/ySOSYhaCCRcH3t9agsco3ToUwoHxMZJ3r1PhEHlM.jpeg
Are you sure that your image stored in public/public folder?
asset() helper generate a asset path from public folder. So, in your property $site->path you getting a path to your image like 'public/yourimage.jpeg'. Try to remove 'public' from your $site->path.
The solution.
In filesystems.php local disk was specified as a default disk. According to docs local disk is supposed to be invisible for public and stored inside storage/app. Thus I was trying to save my file using local disk and accessing it with path public/....
Option #1
Change in filesystems.php default disk to public and use Storage::url() to get url to image.
Option #2
Use $file->store('path', 'public') and Storage::disk('public')->url('path')
So that used disk is specified explicitly.
The given path will contain link close to http://example.com/storage/path.

Saving uploaded image file in public dir not working in laravel 5.6

I have created a designated location to store all the uploaded images in public dir like this:
and I have the default config/filesystem.php for public driver like this:
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'url' => env('APP_URL').'/storage',
'visibility' => 'public',
],
Within my repository, I am trying to save the uploaded image like this:
// ... snipped
if (array_key_exists('logo', $validated)) {
$logoPath = $validated['logo']->store(
'uploads/logos',
'public'
);
$company->logo = url($logoPath);
}
$company->save();
In the database, I can see the value of logo field for the company record like this: http://my-app.local/uploads/logos/3hlsAhnnIPjd4zhdpfhvKw4tqDkpcCz23NczwhVM.png
However, the public/uploads/logos dir is empty. Any idea what might be wrong here? Am I supposed to use the ->move() method on the UploadedFile instead of ->store()?
You can use an alternative method for uploading images in your public directory.
$request->validate([
'logo' => 'image|required',
]);
if($request->hasFile('logo')){
$company->logo = $request->image->move('uploads/logo', $request->logo->hashName());
}
$company->save()
Actually, yes, it was your mistake, but not the one you just found. By default laravel local storage points to storage/app/public directory, because laravel wants you to act professionally and store all uploaded files in storage, not in some kind of public directory. But then you would ask - how on earth user should access non-public storage directly? And there is a caught - php artisan storage:link command. It creates symbolic link from public directory to storage directory (storage/app/public -> public/storage). This is mostly because of deployments and version management.

Laraver rewrite language file from controller

Is it possible to write to a language file located at resources/lang/en/file.php from a controller? I moved my translations to database so user can edit them and now want to write the content from database to lang file each time content is changed.
You can write to anywhere in your filesystem provided you have the correct permissions. file_put_contents will write your contents to the desired path.
But you have the translation in a db, what's the use of writing to a file? You're just creating redundant data unnecessarily.
Edit:
You should define an entry in config/filesystems.php to use with the Storage facade.
'translations' => [
'driver' => 'local',
'root' => resource_path('translations'),
],
Found this function that helps me to write to resources folder:
app()['path.lang']

How to upload files in Laravel directly into public folder?

The server which I'm hosting my website does not support links so I cannot run the php artisan storage:link to link my storage directory into the public directory. I tried to remake the disk configuration in the filesystems.php to directly reference the public folder but it didn't seems to work either. Is there a way to upload a file using Laravel libraries directly into the public folder or will I have to use a php method?
You can create a new storage disc in config/filesystems.php:
'public_uploads' => [
'driver' => 'local',
'root' => public_path() . '/uploads',
],
And store files like this:
if(!Storage::disk('public_uploads')->put($path, $file_content)) {
return false;
}
You can pass disk to method of \Illuminate\Http\UploadedFile class:
$file = request()->file('uploadFile');
$file->store('toPath', ['disk' => 'public']);
or you can create new Filesystem disk and you can save it to that disk.
You can create a new storage disk in config/filesystems.php:
'my_files' => [
'driver' => 'local',
'root' => public_path() . '/myfiles',
],
in controller:
$file = request()->file('uploadFile');
$file->store('toPath', ['disk' => 'my_files']);
You should try this hopping you have added method="post" enctype="multipart/form-data" to your form. Note that the public path (uploadedimages) will be moved to will be your public folder in your project directory and that's where the uploaded images will be.
public function store (Request $request) {
$imageName = time().'.'.$request->image->getClientOriginalExtension();
$request->image->move(public_path('/uploadedimages'), $imageName);
// then you can save $imageName to the database
}
inside config/filesystem.php, add this :
'public_uploads' => [
'driver' => 'local',
'root' => public_path(),
],
and in the controller
$file = $request->file("contract");
$ext = $file->extension();
$filename = $file->storeAs('/contracts/', $contract->title.'.' . $ext,['disk' => 'public_uploads']);
I figured out the fix to this issue , in the config/filesystem.php add this line 'default' => 'public', in my case that fixed for me.
The most flexible is to edit .env file:
FILESYSTEM_DRIVER=public
In addition to every answer there, I would suggest to add another protection layer because it's a public folder.
For every file that you will have in your public folder that requires protection, do a route that will verify access to them, like
/files/images/cat.jpg
and route that looks like /files/images/{image_name} so you could verify the user against given file.
After a correct validation you just do
return response($full_server_filepath, 200)->header('Content-Type', 'image/jpeg');
It makes a work little harder, but much safer
The recommended way is to symlink the storage from the public directory.
To make these files accessible from the web, you should create a
symbolic link from public/storage to storage/app/public. Utilizing
this folder convention will keep your publicly accessible files in one
directory that can be easily shared across deployments when using zero
down-time deployment systems like Envoyer.
To create the symbolic link, you may use the storage:link Artisan
command:
Step 1: change setting in Filesystems.php
'disks' => [
'local' => [
'driver' => 'local',
'root' => storage_path('app'),
],
'public' => [
'driver' => 'local',
'root' => public_path('app/public'),
'url' => env('APP_URL').'/storage',
'visibility' => 'public',
],
Step 2: in Controller: Store file like this:
'indoc_file' => $request->indoc_file->store('app/file'),
Step 3: Go to file .ENV and change the Config like this:
FILESYSTEM_DRIVER=public
After that your file Location will be saved in Project like this:
Project\public\app\public\app\file
if you want to download file able do this on your view page:
<i class="fa fa-download"></i>
as alternative,
let laravel set the file stored in /storage/app folder.
if we want to read the file, just use like $publicPath = '../storage/app/'.$path;

Laravel 5 File Delete Error

There is an issue related to my laravel 5 web application regarding the file deletion.
I want to delete an entry from my table with corresponding image file.
Here is my table structure.
Schema::create('master_brands',function($table){
$table->increments('pk_brand_id');
$table->string('brand_name');
$table->string('brand_logo');
$table->timestamps();
});
I added 3 brands to db and storing image path in brand_logo field like : (/uploads/masters/logocatagory_Computers & IT.png).
When deleting the record from database I want to delete the image file from uploads folder also.
But the File was not deleting when I performing delete action.
here is my delete controller.
public function branddelete($id)
{
$filename = DB::table('master_brands')->where('pk_brand_id', $id)->get();
$filname = url()."/app".$filename[0]->brand_logo;
File::delete($filname); // http://localhost/genie-works/devojp/app//uploads/masters/logocatagory_Computers & IT.png
}
The file is exist in my directory and the directory having 777 permission. !!
I also tried the Storage class to delete file.But there is no way !!!..
How can I solve this issue? Any Ideas... :(
You are doing it the wrong way. You can't possibly delete a file from URL, you must provide file PATH not URL
Edited
Assuming the file you wish to delete is located in public/uploads/masters/logocatagory_Computers you could do this:
public function branddelete($id)
{
$filename = DB::table('master_brands')->where('pk_brand_id', $id)->get();
$filname = $filename[0]->brand_logo;
//example it.png, which is located in `public/uploads/masters/logocatagory_Computers` folder
$file_path = app_path("uploads/masters/logocatagory_Computers/{$filname}");
if(File::exists($file_path)) File::delete($file_path);
}
If you have the file out Storage/app/ , Storage:: does not work, change the /Config/Filesystems.php try put your 'local' at base_path() and comment default storage_path(),
'disks' => [
'local' => [
'driver' => 'local',
'root' => base_path(),
// 'root' => storage_path('app'),
],
Then in Controller
use Illuminate\Support\Facades\Storage;
Then in public funtion use Storage Model
$path= 'uploads/masters/';
Storage::delete($path . $filname);
In Laravel 5.1. When using the local driver, note that all file operations are relative to the root directory defined in your configuration file. By default, this value is set to the storage/app directory. Therefore,
the following method would store a file in storage/app/file.txt:
Storage::put('file.txt', 'Contents');
this would delete file.txt in storage/app
Storage::delete('file.txt');
If you want to change the root directory,take 'storage/app/uploads/' for example , you could set the filesystem.php as following :
'disks' => [
'local' => [
'driver' => 'local',
'root' => storage_path('app/uploads/'),
],
...
then this following method would store a file in storage/app/uploads/file.txt:
Storage::put('file.txt', 'Contents');
this would delete file.txt in storage/app/uploads directory.
Storage::delete('file.txt');
Something that took me quite some time to figure out today:
In case you're trying to delete a list of files that are wrapped in Laravel's own Collection wrapper, you might need to call ->all() to get the underlying array instance:
// The following is an example scenario
$files = Storage::list('downloads');
$collection = collect($files)->filter(function ($file) {
return str_contains($file, 'temp');
});
Storage::delete($collection->all()); // Note the "all()" call here

Categories