Add base URL to images in Laravel
The asset
function generates a URL for an asset using the current scheme of the request (HTTP or HTTPS):
$url = asset('img/photo.jpg');
You can configure the asset URL host by setting the ASSET_URL
variable in your .env
file. This can be useful if you host your assets on an external service like Amazon S3:
// ASSET_URL=http://example.com/assets
$url = asset('img/photo.jpg'); // http://example.com/assets/img/photo.jpg
Example how to use asset() in JsonResource
class UserResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'logo' => asset($this->logo),
'email' => $this->email,
];
}
}