i have table 'case' that contains an image column, i want users to insert into the case table and be able to upload an image, on the home page users can view cases along with image of each case.
so far i have tried:
public function createcase(Request $request){
$validator = Validator::make($request->all(), [
'title' => 'required',
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
'description' => 'required',
'caseTypeId' => 'required',
'amountneeded' =>'required',
'uid' => 'required',
'visible' => 'required',
]);
if ($validator->fails()) {
return response()->json(['error'=>$validator->errors()], 401);
}
$image = $request->file('image');
$path = $image->store('public');
$case = casee::create([
'title' => $request->title,
'description' => $request->description,
'caseTypeId' => $request->caseTypeId,
'amountneeded' => $request->amountneeded,
'uid' => $request->uid,
'visible' => $request->visible,
'image' => $path,
]);
return response()->json(['image' => $image]);
to upload:
<input type="file" id="image" #change="onFileChange" />
methods: {
onFileChange(e) {
this.image = e.target.files[0];
},
async postcase() {
const formData = new FormData();
formData.append('title', this.title);
formData.append('description', this.description);
formData.append('amountneeded', this.amountneeded);
formData.append('caseTypeId', this.selectedcasetype);
formData.append('uid', this.uid);
formData.append('visible', 1);
formData.append('image', this.image);
try {
await axios.post('http://127.0.0.1:8000/api/postcase', formData).then(response => {
console.log(response.data);
})
} catch (error) {
console.log(response.data);
}
}
to retrieve:
<v-flex class="ma-2" v-for="casee in cases" :key="casee.id" lg3 xs12 md6 sm4>
<img v-if="casee.image" :src="'/storage/' + casee.image" alt="Case Image">
mounted(){
this.getcases();
},
methods:{
async getcases(){
try {
const response = await axios.get('http://127.0.0.1:8000/api/cases');
this.cases = response.data.cases;
console.log(this.cases);
} catch (error) {
console.log(error);
}
},
everything works fine except for the image. it returns the error Cannot GET /storage/public/CQu7g4X98APkiMSbCGlqyiJhaXzLaEk8P0pZXaD3.jpg when i try to retrieve it
Frontend couldn't access filesystem as "/storage/public/FILENAME.jpg".
If you are based on Laravel 9.x, and didn't change any filesystem default settings, your file will stored under "<project root>/storage/app/public/", it's filesystem default path, but frontend can only access your "<project root>/public/" folder, do check list as below might help you slove issue.
1.Make sure you executed php artisan storage:link command, and it will created a symbolic link from your storage path to public path.
If you didn't change settings, it will create link from "<project root>/storage/app/public" to "<project root>/public/storage", once you done command you can see your storage folder under public folder.
You can access "<APP_URL>/storage/FILENAME.jpg" to see if link create success or not, if you ain't get 404 means your link created as well as it should be.
2. Use laravel helper to generate storage url.
Use the asset() helper create a URL to the files.
Your files will under "<project root>/public/storage" after step 1, and your nginx root will access public as default, so you don't need public as your url path anymore.
asset('storage/FILENAME.jpg');
// output will be "<APP_URL>/storage/FILENAME.jpg"
3. (Not required) Check if laravel cached your view.
For some new developer of laravel didn't notice that laravel will cached your view, and they keep thinking that code doesn't work.
You can easily check if laravel cached view by php artisan about command if you are using latest laravel version, and use php artisan view:clear to clear view cache.
Make sure that the storage directory is correctly linked to the public.
You can run this command to make it automatically:
php artisan storage:link
heres how i solved it if anyone comes across this issue :
based on the previous answers:
1. php artisan storage:link
replace 'image' => $path to 'image' => basename($path).
3.<img :src="'http://127.0.0.1:8000/storage/' + casee.image" alt="Case Image">
Related
enter image description here
here's my code below
public function store(Request $request)
{
$validateData = $request->validate([
'pembelian_id' => '',
'pconfirm_pic' => 'image|file|max:5087'
]);
// $validatedData['pconfirm_pic'] = $request->file('pconfirm_pic')->store('payment_confirmation','public');
Payconfirm::create($validateData);
return redirect('/user/purchase/?status_pembayaran=1');
}
match with path where controller store to
Run below artisan command
php artisan storage:link
Read More About
i'm using laravel6, and voyager, i'm creating artisan command for installation use cmd following php artisan make: command EcommerceInstall
, I recopy DataTypesTableSeeder from database/seeder and I rename it by DataTypesTableSeederCustom, I modify my file which I wrote EcommerceInstall.php but it gives me error class [DataTypesTableSeederCustom] does not exist.
i think i forget import the class but i don't know where .
EcommerceInstall.php
public function handle()
{
if ($this->confirm('this well delete all you current data and install the dummy default data, Are you sure ?')) {
File::deleteDirectory(public_path('storage/products/dummy'));
$this->callSilent('storage:link');
$copySuccess = File::copyDirectory(public_path('img/products'),public_path('storage/products/dummy'));
if($copySuccess){
$this->info('images succefully copied to storage folder');
}
$this->call('migrate:fresh', [
'--seed' => true,
]);
$this->call('db:seed', [
'--class' => 'DataTypesTableSeederCustom'
]);
$this->info('Dummy data installed');
}
I'm using ckeditor classic 5, and i'm trying to upload images in it. I downloaded php lib Ckfinder3 php connector, set config.
When i'm trying to load image i have a massage: Cannot upload file *filename*.
Interesting moment, that they are fisically loaded on server: i can view it in directory, that set in my config file and this files are correct:
/var/www/projectfiles/downloadfiles/
The next step i'm check permission and groups: it's www-data 0777.
What can be a reason? Can you give some advice or solution?
Thanks!
UPD: init function
ClassicEditor
.create( document.querySelector( '#material_preview' ), {
ckfinder: {
uploadUrl: '/ckfinder/connector/?command=QuickUpload&type=Images'
}
} )
.catch( error => {
console.error( error );
} );
php config:
$config['authentication'] = function () {
return true;
};
$config['backends']['default'] = array(
'name' => 'default',
'adapter' => 'local',
'baseUrl' => 'http://files.project.com/downloadfiles/',
'root' => '/var/www/projectfiles/downloadfiles/',
'chmodFiles' => 0777,
'chmodFolders' => 0777,
'filesystemEncoding' => 'UTF-8'
);
The connector path looks invalid. For PHP it should be something like:
'/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Files'
Please have a look at CKEditor integration examples in CKFinder demo: https://ckeditor.com/docs/ckfinder/demo/ckfinder3/samples/ckeditor.html
Finally i got it!
The connector path is valid. The problem was in cache folder's permisson in laravel. Be glad if it helps you.
I am trying to add a profile image feature in my app. I am using the TDD approach to do this. The test for uploading profile picture shows green. But when I run the test to update the profile picture, it gives an error. Below is the code:
Controller:
public function store(StoreAvatarRequest $request)
{
$path = $request->file('avatar')->store('avatars');
BasicInformation::updateOrCreate([
'user_id' => auth()->id(),
], [
'user_id' => auth()->id(),
'avatar' => $path,
]);
$this->showAlerts('alert-success', 'Profile Image uploaded successfully');
return redirect()->route('avatar.index');
}
public function update(StoreAvatarRequest $request, $id)
{
$basicProfile = BasicInformation::find($id)->first();
$oldAvatarPath = $basicProfile->avatar;
if ($basicProfile->user_id == auth()->id()) {
$path = $request->file('avatar')->store('avatars');
$basicProfile->avatar = $path;
$basicProfile->update();
Storage::delete($oldAvatarPath);
$this->showAlerts('alert-success', 'Profile Image Updated Successfully');
return redirect()->route('avatar.index');
} else {
// TODO :: Need to add logic here
}
}
Test Case:
public function can_update_profile_picture()
{
$this->actingAs($this->lawyer)->post(route('avatar.store'), [
'avatar' => UploadedFile::fake()->image('avatar.jpg', 600, 600)
]);
$oldImagePath = $this->lawyer->information->avatar;
$this->actingAs($this->lawyer)->put(route('avatar.update', ['id' => $this->lawyer->information->id]), [
'avatar' => UploadedFile::fake()->image('avatar1.jpg', 600, 600)
])
->assertRedirect(route('avatar.index'))
->assertSessionHas('status', 'Profile Image Updated Successfully');
Storage::disk('local')->assertExists($this->lawyer->information->avatar);
Storage::disk('local')->assertMissing($oldImagePath);
}
I am getting the following error when I run the test:
PHPUnit 5.7.19 by Sebastian Bergmann and contributors.
F 1 /
1 (100%)
Time: 298 ms, Memory: 20.00MB
There was 1 failure:
1) Tests\Feature\Dashboard\Lawyer\Account\ProfileImageTest::can_update_profile_picture
Unable to find a file at path [local/c5tjUUQDzU4iKHauJK68Z801I5iaYJ7e3cVQ5iA1.jpeg].
Failed asserting that false is true.
This is a matter of configuration and then preference for using store() or storeAs() methods.
First off you have to configure filesystems.phpto recognize your tests Storage disk as the fake() disk:
'testing' => [
'driver' => 'local',
'root' => storage_path('framework/testing/disks/'),
'visibility' => 'public',
Using that setup allows you to use your APP_ENV value in phpunit.xmlfor defaulting this disk for your tests.
Also, I use the use the storeAs()in my controller so that I can test against the filename I stored in the assertExists() method in my test.
$request->file('avatar')->storeAs('avatar', $request->file('avatar')->getClientOriginalName())
Storage::disk('avatar')->assertExists('avatar.jpg');
This is what works for me and the files are deleted before running each test and clean up is not an issue. You can also do a test for the hashName and use the store() method by getting the responsed and using baseName() to get the name of the new file.
I have added to phpunit.xml next line:
<env name="FILESYSTEM_DRIVER" value="uploads"/>
and while checking
$image = $response->original['logo']; // as the image name get changed in Controller
Storage::disk('uploads')->assertExists("public/uploads/$image");
Others codes are similar as Laravel Doc.
You may Like to check the discussion at Laracast.
I am having trouble storing images in the 'public' folder of the Laravel framework (which I believe is the static content folder? Please correct me if I am wrong).
I am running a seed using faker which generates images and stores the images URL's in a table. This is all working correctly but the seed itself keeps failing as it can't seem to access or find the folder within the public folder I have created. This is my public folder structure:
/public/assets/images
And here is my seed which should save my images into this folder:
<?php
use Illuminate\Database\Seeder;
class ProductsTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
DB::table('products')->truncate();
$faker = Faker\Factory::create();
$limit = 30;
for($i = 0; $i < $limit; $i++) {
DB::table('products')->insert([
'title' => $faker->name,
'SKU' => $faker->name,
'description' => $faker->text,
'created_at' => $faker->dateTime,
'updated_at' => $faker->dateTime,
'images' => $faker->image(URL::to(Config::get('assets.images')) ,800, 600, [], [])
]);
}
}
}#
The 'assets.images' config file is:
<?php
return [
'images' => '/assets/images'
];
When I try and run the seed to populate my database I get the following error:
[InvalidArgumentException]
Cannot write to directory "http://localhost:8931/assets/images"
I cannot see where I am going wrong. Can anyone offer any insight?
Change your call of URL::to with the helper function public_path() like this:
$faker->image(public_path(Config::get('assets.images')) ,800, 600, [], [])
I'm not a laravel expert, but the thrown exception looks like you're trying to write to an url rather than a file path on the disk.
Maybe you want to check if the process owner running the php script has write access to that location.