Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5 how to properly use settings variable in my view

I'm trying to learn laravel since 3 days and i have a little a problem.

In my database i have a table 'settings', which looks like : enter image description here

I need to use this data in EVERY page that i load. I do something like that for load the data in my view :

public function indexFront()
{
    $posts = $this->blog_gestion->indexFront($this->nbrPages);
    $links = str_replace('/?', '?', $posts->render());


    //Here i load my setting
    $setting_gestion = new SettingRepository(new setting());
    $config = $setting_gestion->getSettings('ferulim');


    //Next i pass my setting to my view
    return view('front.blog.index', compact('posts', 'links', 'config'));
}

It works but i need to do that in every controller and every function... I think there is an another way for do the same thing :p

Help me !

like image 712
CanardMandarin Avatar asked Dec 15 '25 08:12

CanardMandarin


1 Answers

You can easily achieve that for selected views or all views using View Composers (http://laravel.com/docs/5.0/views#view-composers).

First, you need to implement a view composer that does the logic that you want to do for every view:

<?php namespace App\Providers;

use View;
use Illuminate\Support\ServiceProvider;

class ComposerServiceProvider extends ServiceProvider {
  public function boot()
  {
    View::composer('*', function($view) {
      $blog_gestion = ...; // fetch or instantiate your $blog_gestion object          
      $posts = $blog_gestion->indexFront($this->nbrPages);
      $links = str_replace('/?', '?', $posts->render());

      $setting_gestion = new SettingRepository(new setting());
      $config = $setting_gestion->getSettings('ferulim');

      $view->with(compact('posts', 'links', 'config'));
    });
  }

  public function register()
  {
    //
  }
}

Next, register your new service provider in providers array in your config/app.php.

That's it :) Let me know if there are any typos/errors, I haven't had a chance to run the code.

like image 79
jedrzej.kurylo Avatar answered Dec 16 '25 22:12

jedrzej.kurylo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!