D
D
Dmitry2016-06-01 18:04:51
Laravel
Dmitry, 2016-06-01 18:04:51

How to use methods of any of your created models in laravel 5 in the service provider class?

I am trying to create a view composer. To do this, I create my own service provider, connect it - everything is according to the instructions.
And inside the boot method I create a composer

view()->composer('lalalala', function($view) {

});

Inside the composer, I need to call one of the methods of my News model.
To do this, I connect the News model through use, i.e.
use App\News;
and in the composer function I do this:
view()->composer('lalalala', function($view) {
     $new = new News; // создаю объект класса News
     $data = $news -> getNews(); // получаю список новостей
     $view ->with('news', $data); // передаю во вьюшку
});

The question is this: I tried in this case to do without creating an object, but to make a dependency injection in this way:
public function boot(News $new)
{
     view()->composer('lalalala', function($view) {
          $new = new News; // создаю объект класса News
          $data = $news -> getNews(); // получаю список новостей
          $view ->with('news', $data); // передаю во вьюшку
     });
}

But it doesn't work. In controllers, such a move works, but not here. Can anyone suggest why?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
D', 2016-06-01
@battrack

Because new News is called in a closure and you need to write it like this:

view()->composer('lalalala', function($view) use ($new) {
          $data = $new -> getNews(); // получаю список новостей
          $view ->with('news', $data); // передаю во вьюшку
     });

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question