首页 > 解决方案 > Laravel 5.6:资源未在一条路线上加载

问题描述

我在我的布局中使用了一个预加载器 gif,它位于 public/img 中,并通过以下代码行使用: <img src="img/preloader.gif" alt="Preloader">

这对于除一条之外的所有路线都非常有效,所述路线定义如下:

Route::get('/test/{name}', function ($name) {
return view('test')->with('name',$name); });

这是“测试”视图:

@extends('layouts.app')

@section('content')

<section>
    <div>
        <h1>{{$name}}</h1>  
    </div>
</section>

@endsection

最后,这是我稍作修改的 filesystems.php,其中“本地”已更改:

<?php

return [

/*
|--------------------------------------------------------------------------
| Default Filesystem Disk
|--------------------------------------------------------------------------
|
| Here you may specify the default filesystem disk that should be used
| by the framework. The "local" disk, as well as a variety of cloud
| based disks are available to your application. Just store away!
|
*/

'default' => env('FILESYSTEM_DRIVER', 'local'),

/*
|--------------------------------------------------------------------------
| Default Cloud Filesystem Disk
|--------------------------------------------------------------------------
|
| Many applications store files both locally and in the cloud. For this
| reason, you may specify a default "cloud" driver here. This driver
| will be bound as the Cloud disk implementation in the container.
|
*/

'cloud' => env('FILESYSTEM_CLOUD', 's3'),

/*
|--------------------------------------------------------------------------
| Filesystem Disks
|--------------------------------------------------------------------------
|
| Here you may configure as many filesystem "disks" as you wish, and you
| may even configure multiple disks of the same driver. Defaults have
| been setup for each driver as an example of the required options.
|
| Supported Drivers: "local", "ftp", "sftp", "s3", "rackspace"
|
*/

'disks' => [

    'local' => [
        'driver' => 'local',
        'root' => storage_path('../public/img/uploads/'),
    ],

    'public' => [
        'driver' => 'local',
        'root' => storage_path('app/public'),
        'url' => env('APP_URL').'/storage',
        'visibility' => 'public',
    ],

    's3' => [
        'driver' => 's3',
        'key' => env('AWS_ACCESS_KEY_ID'),
        'secret' => env('AWS_SECRET_ACCESS_KEY'),
        'region' => env('AWS_DEFAULT_REGION'),
        'bucket' => env('AWS_BUCKET'),
        'url' => env('AWS_URL'),
    ],

],

];

为什么我面临这个问题,解决它的最佳方法是什么?

标签: phphtmllaravelresources

解决方案


您的图像 src 正在使用一种称为相对 URI的东西,它本质上是说“获取当前 URI,并将其添加到它的末尾”。

当您在主页上时example.com,您的图像路径是example.com/img/preloader.gif,这是正确的。

一旦你在一个包含多个段的更深的 URI 上,例如example.com/test/foobar,图像 URI 就变成example.com/test/img/preloader.gif了这显然是不正确的。

在 Laravel 中解决这个问题的最简单和最推荐的方法是使用asset()orsecure_asset()助手。这将有助于生成图像/资产的绝对 URI,并且无论用户在您的应用程序的哪个页面上都是正确的。

<img src="{!! asset('img/preloader.gif') !!}" alt="Preloader">

推荐阅读