Posted: 28-12-2018

Create array key/value from Eloquent query with pluck

Create array key/value from Eloquent query with pluck

In maguttiCms I need to share some site settings value stored in a Settings table to all the front end view.
After some  search I found the pluck method can be a good solution to create an array with keys/values that provides an easy way to get setting values in Front end views.

Here my query : 

$site_settings = Setting::all()->pluck('value','key');

that produces a collection like this:

Collection {#790 ▼
  #items: array:6 [
    "GA_CODE" => "UA-xxxxxxxx"
    "credits_url" => ""
    "GMAPS_KEY" => "UA-xxxxxxxx"

In this way is very easy retreive value using array key using the laravel data_get() helper



If you want to share  the $site_settings array in all your view you can place in the AppServiceProvider.php boot function the following  code

public function boot()
view()->composer('website/*', function(){
$this->site_settings = Setting::all()->pluck('value','key');
view()->share('site_settings', $this->site_settings);

More about Eloquent pluck can be found in Laravel docs at