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中有注释。
答案 0 :(得分:1)
确实$name
属性不存在。尝试:
@inject('siteInfo', 'App\Services\SiteInformation')
<title>{{ $siteInfo->siteInfo->name }}</title>
或者如果是数组:
<title>{{ $siteInfo->siteInfo['name'] }}</title>
根据您的打印件,尝试获取单个项目而不是集合:
public function __construct() {
$this->siteInfo = SiteInfo::first();
}
然后你应该能够做到:
<title>{{ $siteInfo->siteInfo->name }}</title>
答案 1 :(得分:0)
SiteInfo::all()
返回一组行,这里只有一行。
所以你可以这样做:
$rows = SiteInfo::all();
$siteInfo = $rows->first();
但更好的是,只需使用Eloquent的方法:
$siteInfo = SiteInfo::first();