Ion
Ion

Reputation: 39

Laravel asset with sub domain

I need to make asset() work without writing subdomain name:

My Code:

asset('images/logos/logo-partner-5.png')

Code which work but don't want:

asset('subdomain/images/logos/logo-partner-5.png')

Any suggestion?

maybe to not use asset() but other function? exist another way?

or how to config the asset() path?

Upvotes: 1

Views: 3445

Answers (1)

Travis Britz
Travis Britz

Reputation: 5552

Edit:

Laravel 5.7.14 will ship with an asset_url config option to do exactly this.

Original response below:


You can define your own helper function:

function cdn_asset($path, $secure = null) {
    return app('url')->assetFrom(config('app.cdn_subdomain'), $path, $secure);
}

And place the config value in config/app.php:

'cdn_subdomain' => 'http://subdomain.example.com',

Usage:

<img src="{{ cdn_asset('images/logos/logo-partner-5.png') }}">

I named the function cdn_asset() because that seems like the most common situation for serving assets from a different domain, but you can call it whatever you like.


If you always want all assets served from the subdomain, you can override Laravel's asset helper. This might get a little dirty:

If you look in Illuminate\Foundation\helpers.php, you'll see that Laravel checks if the function exists before creating it:

if (! function_exists('asset')) {
    function asset() { ... }
}

Which means you can define the function before Laravel does, and it will use yours instead:

function asset($path, $secure = null) {
    return app('url')->assetFrom('http://subdomain.example.com', $path, $secure);
}

If you create a file called /app/helpers.php to define this function, you need to require it before Laravel loads the /vendor/autoload.php file. As of Laravel 5.7, this happens in /public/index.php. Add your own line before this happens:

require __DIR__.'/../app/helpers.php'; // this is yours
require __DIR__.'/../vendor/autoload.php';

You might also want to require it in the artisan file in the base path of the project.

Upvotes: 3

Related Questions