【问题标题】:Laravel 5.3 : How to inject variables into "layout" page?Laravel 5.3:如何将变量注入“布局”页面?
【发布时间】: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 中有注释。

dd($siteInfo);的结果:

【问题讨论】:

    标签: laravel-5.3


    【解决方案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>
    

    【讨论】:

    • 我无法获取属性值,我添加了 dd() 的结果,请参阅我的编辑。
    【解决方案2】:

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

    所以你可以这样做:

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

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

    $siteInfo = SiteInfo::first();
    

    【讨论】:

      猜你喜欢
      • 2017-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-13
      • 2021-01-18
      • 2017-07-30
      • 2017-02-28
      • 2016-11-20
      相关资源
      最近更新 更多