Reputation: 4232
Laravel 5.3 : How to inject variables into "layout" page?
I tried "Service Injection" , like this:
@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();
}
}
error:
Undefined property: App\Services\SiteInformation::$name (View: D:\wnmp\www\laravel-5-3-dev\resources\views\layouts\app.blade.php)
Questions:
1.How could I modify the code?
2.Are there any other ways to do it?
Edit:
And I tried another way in 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);
});
}
The error is the same:
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)
The location of line 22 has comment in AppServiceProvider.php.
Upvotes: 0
Views: 582
Reputation: 16373
SiteInfo::all()
returns a collection of rows, here it has only one row.
So you could do:
$rows = SiteInfo::all();
$siteInfo = $rows->first();
But better, just use Eloquent's method:
$siteInfo = SiteInfo::first();
Upvotes: 0
Reputation: 14747
Indeed $name
property does not exist. Try:
@inject('siteInfo', 'App\Services\SiteInformation')
<title>{{ $siteInfo->siteInfo->name }}</title>
or if it is an array:
<title>{{ $siteInfo->siteInfo['name'] }}</title>
Based in your print, try to get a single item instead a collection:
public function __construct() {
$this->siteInfo = SiteInfo::first();
}
Then you should be able to do:
<title>{{ $siteInfo->siteInfo->name }}</title>
Upvotes: 1