admin管理员组

文章数量:1384310

** How to get laravel Storage path in js file**

I want to display dinamic image in laravel from database using jquery ajax, but I can't get Stoage path in js file to put my image name which is a variable:

images.forEach(function (image) {  

        var img = `<img src="http://localhost/storage/${product.image}"`;

});

"http://localhost/storage/" works,but I want to replace "http://localhost/storage/" to dinamic url using javascript

** How to get laravel Storage path in js file**

I want to display dinamic image in laravel from database using jquery ajax, but I can't get Stoage path in js file to put my image name which is a variable:

images.forEach(function (image) {  

        var img = `<img src="http://localhost/storage/${product.image}"`;

});

"http://localhost/storage/" works,but I want to replace "http://localhost/storage/" to dinamic url using javascript

Share Improve this question edited Feb 8, 2019 at 7:44 Hayk Margaryan asked Feb 8, 2019 at 7:36 Hayk MargaryanHayk Margaryan 331 silver badge5 bronze badges 5
  • Can you try this localhost{project_name}/public/storage/ – Kiran Kanzar Commented Feb 8, 2019 at 7:38
  • Thanks a lot, and if my project runs on a non-local server, does it work? – Hayk Margaryan Commented Feb 8, 2019 at 7:41
  • @HaykMargaryan In master blade file of your view you can define a global js variable to use the storage path and then you can use that variable inside this file. – Kamal Paliwal Commented Feb 8, 2019 at 7:44
  • Are you using the public file system driver? Because the storage path should NEVER be exposed directly. – Jerodev Commented Feb 8, 2019 at 7:46
  • No, its working only for local server, if your project url changed links broken at that time. – Kiran Kanzar Commented Feb 8, 2019 at 7:55
Add a ment  | 

3 Answers 3

Reset to default 3

Use a relative path, which will fix the issue in any server. As follows

images.forEach(function (image) {  
 var img = `<img src="/storage/${product.image}"`;
});

To get laravel storage path in js file you can do like:

In your headerfile.blade.php

<script>

var storagePath = {!! storage_path() !!}; // old with error

var storagePath = "{!! storage_path() !!}"; // updated and tested
</script>

The in js file you can use storagePath variable.

I hope this will help you.

For that either 1.

{!! storage_path('app/public') !!}

2.you can pass it with your data of product

or

3.you use model for set the full src of image

protected $appends = ['image_url'];
public function getImageUrlAttribute()
    {
        $imageUrl = "";
        if (isset($this->attributes['image']) && $this->attributes['image'] != "") {
            $imageUrl = storage_path('app/public').$this->attributes['image'];
        }
        return $imageUrl;
    }

and you can use them in your blade like

images.forEach(function (image) {  

        var img = `<img src="${product.image_url}"`;

});

本文标签: How to get laravel storage path using javascriptStack Overflow