how to pass a variable to service provider in Laravel?

限于喜欢 提交于 2021-02-09 09:15:07

问题


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?


回答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.



来源:https://stackoverflow.com/questions/34222514/how-to-pass-a-variable-to-service-provider-in-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!