Laravel 5.3 : 如何将变量注入 "layout" 页面?

Laravel 5.3 : How to inject variables into "layout" page?

Laravel 5.3 : 如何将变量注入"layout"页面?

我试过 "Service Injection" ,像这样:

@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.How我可以修改代码吗?
2.Are还有其他方法吗?

编辑:

我在 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中有注释。

dd($siteInfo);的结果:

的确$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>

SiteInfo::all() returns行的集合,这里只有一行。

所以你可以这样做:

$rows = SiteInfo::all();
$siteInfo = $rows->first();

但更好的是,使用Eloquent的方法:

$siteInfo = SiteInfo::first();