【发布时间】:2016-10-11 19:25:57
【问题描述】:
Laravel 5.3:如何将变量注入“布局”页面?
我试过“服务注入”,像这样:
@inject('siteInfo', 'App\Services\SiteInformation')
<title>{{ $siteInfo->name }}</title>
<meta name="keywords" content="{{ $siteInfo->keywords }}"/>
<meta name="description" content="{{ $siteInfo->description }}"/>
SiteInformation.php
<?php
namespace App\Services;
use App\SiteInfo;
class SiteInformation
{
public $siteInfo;
public function __construct() {
$this->siteInfo = SiteInfo::all();
}
}
错误:
Undefined property: App\Services\SiteInformation::$name (View: D:\wnmp\www\laravel-5-3-dev\resources\views\layouts\app.blade.php)
问题:
1.如何修改代码?
2.还有其他方法吗?
编辑:
我在AppServiceProvider.php尝试了另一种方式
public function boot()
{
view()->composer('layouts/app', function ($view) {
$siteInfo=SiteInfo::all();
dd($siteInfo);
$view->with('siteName',$siteInfo->name) // this is line 22
->with('siteKeywords',$siteInfo->keywords)
->with('siteDescription',$siteInfo->description);
});
}
错误是一样的:
ErrorException in AppServiceProvider.php line 22:
Undefined property: Illuminate\Database\Eloquent\Collection::$name (View: D:\wnmp\www\laravel-5-3-dev\resources\views\pages\index.blade.php)
第 22 行的位置在 AppServiceProvider.php 中有注释。
【问题讨论】:
标签: laravel-5.3