How to generate DigitalOcean Spaces CDN url on Laravel ?

January 4, 2019 2.4k views
PHP Frameworks Development Ubuntu PHP


I am using Storage class for getting file url like this;

//This gives :

But I dont want orginal file url, I wanna CDN file url like this ;

I prefer clean code instead of string manipulation

2 Answers

I know you said no string manipulation but i currently have the same problem and the only clean way I solved it for my self is to put it in a method:

public function getExampleAttributeStoragePath(){
            return str_replace("digitaloceanspaces","cdn.digitaloceanspaces",Storage::url($this->exampleAttribute));
            return null;

But I also hope for a cleaner code, hope this helps as a quick fix for now

or you can also edit the url attribute in the filesystem config like this

'spaces' => [
            'driver' => 's3',
            'key' => env('DO_SPACES_KEY'),
            'secret' => env('DO_SPACES_SECRET'),
            'endpoint' => env('DO_SPACES_ENDPOINT'),
            'region' => env('DO_SPACES_REGION'),
            'bucket' => env('DO_SPACES_BUCKET'),
            'url' => str_replace(env('DO_SPACES_REGION'),env('DO_SPACES_BUCKET').'.'.env('DO_SPACES_REGION'),str_replace("digitaloceanspaces","cdn.digitaloceanspaces",env('DO_SPACES_ENDPOINT'))),

its a bit messy but does the job also this way its stored in the cache

@fatmabensoy @omartuffaha
so as you have the spaces registered in the config/filesystem.php, where you specify your endpoint? (if it allows CDN. Currently SFO2 and NYC3 I think, I’d verify)

I just changed my endpoint in my .env file to the following and it serves it all as CDN without any manipulation


that made them all automatically serve up as {spacename]

Hope this helps!

Have another answer? Share your knowledge.