我是laravel的新手。我试图用一些变量来创建一个简单的应用程序。所以我创建了一个设置模型,包含许多字段和一个独特的段塞字段。现在,为了从数据库中共享这个变量,我创建了一个中间件:
public function handle($request, Closure $next)
{
$site_settings = Cache::remember('settings', 60, function() {
return Setting::all();
});
view()->share('site_settings', $site_settings);
return $next($request);
}
现在在视图中显示此变量我有:
{{{ $site_settings->get(0)->value }}}
这很有效,但我想在我的视图中使用更直观的代码,通过slug访问设置。类似的东西:
{{{ $site_settings->findBySlug("MYVARIABLE")->value }}}
所以可以通过一个独特的slug过滤收集?
答案 0 :(得分:1)
这假设您的设置表结构如下:
----------------------
| id | key | value |
----------------------
| 1 | title | foo |
| 2 | asd | bar |
| 3 | qqq | zzz |
----------------------
第1步:将以下newCollection
方法放入 App \ Setting 模型中:
class Settings extends ... {
public function newCollection(array $models = array())
{
return new \App\Collections\SettingsCollection($models);
}
}
第2步:将以下行放入 App \ Collections \ SettingsCollection 类:
<?php namespace App\Collections;
use Illuminate\Database\Eloquent\Collection;
class SettingsCollection extends Collection {
public function get($name, $default = null)
{
return array_first($this->items, function($itemKey, $model) use ($name)
{
return $model->key == $name;
}, $default)->value;
}
}
第3步:享受!这是我目前正在使用的系列。 而不是:
$settings = Setting::all();
$settings->where('key', 'key_name')->first()->value;
您只需执行此操作:
$settings = Setting::all();
echo $settings->get('key_name'); // returns value of the setting with the key 'title'
答案 1 :(得分:0)
可能适合查询范围。
在你的模特中:
The method `getThreadLocalRequest()` from the type `AbstractRemoteServiceServlet` is not visible
所以你将拥有:public function scopeFindBySlug($slug){
return $query->where('slug','=', $slug);
}