Share value from database in all view in laravel 5 -
i'm new laravel. i'm trying create simple app variable shouold in every view. create setting model, many fields , unique slug field. share variable database i've created middleware:
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); }
now show variable in view have:
{{{ $site_settings->get(0)->value }}}
this works great, i'd have more intuitive code in view, accessing setting slug. like:
{{{ $site_settings->findbyslug("myvariable")->value }}}
so it's possible filter collection unique slug?
info:
this assumes settings table structure following:
---------------------- | id | key | value | ---------------------- | 1 | title | foo | | 2 | asd | bar | | 3 | qqq | zzz | ----------------------
steps
step 1: put following newcollection
method app\setting model:
class settings extends ... { public function newcollection(array $models = array()) { return new \app\collections\settingscollection($models); } }
step 2: put following lines app\collections\settingscollection class:
<?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; } }
step 3: enjoy! collection i'm using. instead of this:
$settings = setting::all(); $settings->where('key', 'key_name')->first()->value;
you can this:
$settings = setting::all(); echo $settings->get('key_name'); // returns value of setting key 'title'
Comments
Post a Comment