3

I want to generate a dynamic menu in a sidebar and share with all the views in Laravel 5.1.

like:

- Marks Module
    - Langosh Topic
       - Content 1
       - Content 2
    -Nitzsche Topic
       - Content 3
- Rolfson Module

Although All this elements belong another entity called course which I can select in the Top menu (users can have more than 1 course).

So every time that I access, Course, Module, Topic or Content they need to tell the sidebar menu which course is the father (or grandfather) of all of those kids to generate the menu.

in AppServiceProvider I have view composer and everything's working fine, but I am using sessions to get the course ID, and I don't like to idea.

How can I pass the $course to the Service Provider or is there any other better way to do that?

Nick Bondarenko
  • 6,211
  • 4
  • 35
  • 56
Leonardo Beal
  • 724
  • 11
  • 24
  • why don't you call the view composer from your controllers ? – Moppo Dec 11 '15 at 11:47
  • If I have to call the view composer from my controllers, I might just pass the var to the view I am loading in each controller and that does the job. That might actually be the answer. – Leonardo Beal Dec 11 '15 at 12:01
  • 1
    Where do ou load `$course`? If you are doing so in your controller, there is no way to pass it to the service provider since it has already loaded by then. – marstato Dec 11 '15 at 12:14
  • yes, I am loading $course in controllers. Any better solution, then? I really didn't want to manually pass it in every action in every controller. It has to have a better way – Leonardo Beal Dec 11 '15 at 12:42

1 Answers1

1

Actually, you should not try to pass a variable to a service provider in this case. If need comes, this could be done using Laravel's container, because it's global and it's initialized at the application start up.

But since you just build menu, I would recommend to delegate menu building to a specific class. Create an instance of this class in controllers and pass it to the view. Call it's methods, iterate it's properties to get menu structure.

If you have various application parts providing information about this side-menu, you could utilize events to gather menu pieces together.

Vladislav Rastrusny
  • 29,378
  • 23
  • 95
  • 156