使用路由 Laravel 5.2 时访问资源时出错

Posted

技术标签:

【中文标题】使用路由 Laravel 5.2 时访问资源时出错【英文标题】:Error accessing resources while using routes Laravel 5.2 【发布时间】:2018-07-25 20:08:19 【问题描述】:

主页页面,我可以访问bootstrap、javascript和图像等资源,然后从主页访问新闻页面,然后从新闻页面访问newsDetail 页面。但是在这个newsDetails 页面中,它访问了错误的资源地址。 例子 : 在主页中,它可以正确访问 http://localhost:8000/css/bootstrap.min.css http://localhost:8000/img/Logo.png

但在 newsDetails 页面中,它访问 http://localhost:8000/news/css/bootstrap.min.css http://localhost:8000/news/img/Logo.png

地址上有以下“新闻”。 这是我的路线

Route::get('/','HomeController@showHome');
Route::get('news','NewsController@showNews');
Route::get('news/id','NewsController@showNewsDetails');

控制器

public function showNewsDetails($id)
    
        $content = News::find($id);
        return view('newsDetails',compact('content'));
    

谁能帮忙?

【问题讨论】:

显示您的查看代码 在您添加 bootstrap.min.css 和 Logo.png 的位置显示您的代码 【参考方案1】:

您应该将所有 CSS/JS 内容放入公共文件夹,您可以使用 asset() helper 访问它

<link href = " asset('public') /css/bootstrap.css" rel = "stylesheet" type = "text/css">

为标志

<img src=" asset('public') /img/Logo.png" />

【讨论】:

【参考方案2】:

如果您的应用程序使用 HTTPs(目前大多数情况下):

使用secure_asset()secure_url()

secure_asset 函数使用 HTTPS 为资产生成 URL:

secure_url 函数为给定路径生成一个完全限定的 HTTPS URL:

试试:

$url = secure_asset('img/Logo.png');

$url = secure_url('user/profile');

【讨论】:

【参考方案3】:

您可以使用url() 助手:

<link rel="stylesheet" href="url('/website/plugins/bootstrap/css/bootstrap.min.css')">

或在链接开头使用/

<link rel="stylesheet" href="/website/plugins/bootstrap/css/bootstrap.min.css">

【讨论】:

【参考方案4】:

使用asset() 助手来避免此类问题:

<img src=" asset('img/Logo.png') ">

【讨论】:

以上是关于使用路由 Laravel 5.2 时访问资源时出错的主要内容,如果未能解决你的问题,请参考以下文章

Laravel 5.2 - 使用 composer 和 git bash 安装 laravel 时出错

如何在 Laravel 5.2 中使用资源声明路由

提交表单时使用路由参数传递变量Laravel 5.2

在 laravel 5.2 中创建符号链接时出错?

在 forge 上安装 Laravel 5.2 时出错

只能访问 Laravel 5.2 中的 / 路由